Sending email in .NET MVC through Gmail

This articale will show you how to send mail through your gmail account, using your gmail credential.

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail

   public ActionResult Index()
    {
        var fromAddress = new MailAddress("from@gmail.com", "From Name");
        var toAddress = new MailAddress("to@example.com", "To Name");
        const string fromPassword = "fromPassword";
        const string subject = "Subject";
        const string body = "Body";
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment("d:/att/textfile.txt");
        try
        {
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body,

            })
            {
                message.Attachments.Add(attachment);
                smtp.Send(message);
            }
        }
        catch (Exception ex)
        { }
        return View();
    }
Advertisements
This entry was posted in C#.NET, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s