How can I send email using Gmail SMTP in asp.net mvc application?

send emails by using email templates in asp.net mvc using c#
how to send email in asp.net mvc5
send mail in asp.net c# using gmail
asp net 4.5 send email
send mail asynchronously asp net mvc
the smtp server requires a secure connection or the client was not authenticated.
send email using asp net web api
how to send email automatically in mvc 4

I want to send one mail to user whenever he/she register at my website.

I have created my gmail account for that, I've tried many samples from net but i'm not able to sent email yet.

Please help me in this regard.

Thanks, vicky

I found a very good article on a website https://askgif.com about using Gmail SMTP with C#, so am sharing with you : https://askgif.com/blog/122/seding-email-using-gmail-smtp-in-asp-net-mvc-application/

Create Gmail Class comprises of all needed data type and member function as below

public class GMailer
{
    public static string GmailUsername { get; set; }
    public static string GmailPassword { get; set; }
    public static string GmailHost { get; set; }
    public static int GmailPort { get; set; }
    public static bool GmailSSL { get; set; }

    public string ToEmail { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public bool IsHtml { get; set; }

    static GMailer()
    {
        GmailHost = "smtp.gmail.com";
        GmailPort = 25; // Gmail can use ports 25, 465 & 587; but must be 25 for medium trust environment.
        GmailSSL = true;
    }

    public void Send()
    {
        SmtpClient smtp = new SmtpClient();
        smtp.Host = GmailHost;
        smtp.Port = GmailPort;
        smtp.EnableSsl = GmailSSL;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(GmailUsername, GmailPassword);

        using (var message = new MailMessage(GmailUsername, ToEmail))
        {
            message.Subject = Subject;
            message.Body = Body;
            message.IsBodyHtml = IsHtml;
            smtp.Send(message);
        }
    }
}

Then just used the following code wherever you want to send the email to the required email account.

GMailer.GmailUsername = "youremailid@gmail.com";
        GMailer.GmailPassword = "YourPassword";

        GMailer mailer = new GMailer();
        mailer.ToEmail = "sumitchourasia91@gmail.com";
        mailer.Subject = "Verify your email id";
        mailer.Body = "Thanks for Registering your account.<br> please verify your email id by clicking the link <br> <a href='youraccount.com/verifycode=12323232'>verify</a>";
        mailer.IsHtml = true;
        mailer.Send();

Hope this will help you. Mark as answer if this helps you.

How can I send email using Gmail SMTP in asp.net mvc application , In this article, you will learn to send Email using Gmail SMTP. Here, we will see how can we send email using our Gmail SMTP in c# .NET. Generally, for sending an email from one Turn this ON (Allow less secure app). C#. I want to send one mail to user whenever he/she register at my website. I have created my gmail account for that, I've tried many samples from net but i'm not able to sent email yet. Please help

Here is a Email class that can be used with ASP.NET MVC4 leveraging dependency injection. A full running sample application & unit tests that use this class can be found here in my github space https://github.com/fredo007/i6technology/tree/master/InsuranceSales.

I've also put together an article explaining methodology & use here http://prestoasp.net/how-to-send-email-using-gmail-smtp-in-an-asp-net-mvc-application/

public class GmailEmailService : IEmailService
{
    private readonly SmtpConfiguration _config;

    private const string GmailUserNameKey = "GmailUserName";
    private const string GmailPasswordKey = "GmailPassword";
    private const string GmailHostKey = "GmailHost";
    private const string GmailPortKey = "GmailPort";
    private const string GmailSslKey = "GmailSsl";

    public GmailEmailService()
    {
        _config = new SmtpConfiguration();
        var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
        var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
        var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
        var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
        var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
        _config.Username = gmailUserName;
        _config.Password = gmailPassword;
        _config.Host = gmailHost;
        _config.Port = gmailPort;
        _config.Ssl = gmailSsl;
    }

    public bool SendEmailMessage(EmailMessage message)
    {
        var success = false;
        try
        {
            var smtp = new SmtpClient
            {
                Host = _config.Host,
                Port = _config.Port,
                EnableSsl = _config.Ssl,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(_config.Username, _config.Password)
            };

            using (var smtpMessage = new MailMessage(_config.Username, message.ToEmail))
            {
                smtpMessage.Subject = message.Subject;
                smtpMessage.Body = message.Body;
                smtpMessage.IsBodyHtml = message.IsHtml;
                smtp.Send(smtpMessage);
            }

            success = true;
        }
        catch (Exception ex)
        {
            //todo: add logging integration
            //throw;
        }

        return success;
    }
}

Send Email Using Gmail SMTP, How do you fix the SMTP server requires a secure connection or the client was not authenticated? Here Mudassar Ahmed Khan has explained a short tutorial with example on how to send emails using SMTP Server in ASP.Net MVC 5 Razor. This article will make use of GMAIL SMTP Server for sending emails in ASP.Net MVC 5 Razor.

In addition to fredo Answer to clear web.config section

public GmailEmailService()
{
    _config = new SmtpConfiguration();
    var gmailUserName = ConfigurationManager.AppSettings[GmailUserNameKey];
    var gmailPassword = ConfigurationManager.AppSettings[GmailPasswordKey];
    var gmailHost = ConfigurationManager.AppSettings[GmailHostKey];
    var gmailPort = Int32.Parse(ConfigurationManager.AppSettings[GmailPortKey]);
    var gmailSsl = Boolean.Parse(ConfigurationManager.AppSettings[GmailSslKey]);
    _config.Username = gmailUserName;
    _config.Password = gmailPassword;
    _config.Host = gmailHost;
    _config.Port = gmailPort;
    _config.Ssl = gmailSsl;
}

Now add in web.config file

<configuration>
    <appSettings>
        <add key="GmailUserNameKey" value="sender@gmail.com"/>
        <add key="GmailPasswordKey" value="senderPassword"/>
        <add key="GmailHostKey" value="smtp.gmail.com"/>
        <add key="GmailPortKey" value="25"/>
        <add key="GmailSslKey" value="true"/>
</appSettings>

Sending email using Gmail SMTP in asp.net mvc application?, You can use GMAIL SMTP service to send emails using c# .net MVC. You can specify the property constants in a config file for easy alteration. In this article, we will learn how to send emails using SMTP Server in ASP.NET MVC with Web API. There are many ways to send an email - SMTP, POP3, IMAP, Exchange Web Services, Outlook Interop, etc. Here, we will use SMTP (Gmail).

Here is my solution for it, first time posting an answer. Happy coding

[HttpPost]
[ValidateAntiForgeryToken]
public async Task < ActionResult > Contact(EmailFormModel model) {
    if (ModelState.IsValid) {
        var body = "<p>Email From: {0} ({1})Message:</p><p>{2}</p>";
        var message = new MailMessage();
        //message.To.Add(new MailAddress("recipient@gmail.com"));  // replace with valid value 
        message.To.Add(new MailAddress("haha")); // replace with valid value 
        //message.From = new MailAddress("sender@outlook.com");  // replace with valid value
        message.From = new MailAddress("hahaha"); // replace with valid value,you cannot commend it, since it's required
        message.Subject = "Your email subject";
        message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
        message.IsBodyHtml = true;

        using(var smtp = new SmtpClient()) {
            var credential = new NetworkCredential {
                UserName = "emailAddress", // replace with valid value
                    Password = "yourPassword" // Password = "password"  // replace with valid value
            };
            //smtp.Credentials = credential;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential("your emailAddress", "Password"); //You will be receive email from this email address
            //smtp.Host = "smtp-mail.outlook.com";
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(message);
            return RedirectToAction("Sent");
        }
    }
    return View(model);
}

Send Email using SMTP Server in ASP.Net MVC, This article will make use of GMAIL SMTP Server for sending emails in ASP.Net MVC 5 Razor. Note: For beginners in ASP.Net MVC, please referĀ  At least one of your problems is that you need to tell the SMTP client to not use your windows credentials before you provide the username and password of the gmail account. Add. smtp.UseDefaultCredentials = false; above this line of code (NOT after). smtp.Credentials = new System.Net.NetworkCredential("my_valid_email@gmail.com", "my_valid_pass");

ASP.NET MVC Send Email Using Gmail SMTP In AngularJS c# , mvcemail #gmailsmtpmvc #angularjsmvc sending an Emaill using the gmail SmtpClient class Duration: 24:28 Posted: Jul 9, 2019 Sending Email using Contact Form in ASP.Net When the SendButton is clicked, the Sender email address (from) is fetched from the SmtpSectionof the Web.Config file, the Subject and Body are fetched from their respective TextBoxes in the Contact Us Form and all these values are set into an object of the MailMessageclass.

Email sending in ASP.NET MVC, Send email programmatically using Gmail smtp server.Duration: 2:31 Posted: Mar 22, 2019 The solution to the problem was this. I ended up using winhosts SMTP. My email is hosted is hosted on google. I couldn't send to an email address that was of the same domain as my hosting company though because it looked there first for the email address. When it didn't find it it errored out.

ASP.NET Core MVC Send Email To Gmail SMTP Code Visual , sendmailgmail #asp.netcoreemail sending email to gmail host smtp account in asp.net core Duration: 17:50 Posted: Nov 20, 2019 You will need an SMTP server to send email from. No idea how GoDaddy works but I'm sure they will provide something. To send emails from an MVC app you either specify you SMTP details in code or in the web.config. I recommend in the config file as it means it's much easier to change.

Comments
  • Great help, Thanks!
  • Can you please add the web.config part. That will make this answer complete. :)