Thursday, October 31, 2013

Send Email From ASP.Net using Gmail as SMTP Client

Day before yesterday, I faced a very unusual problem in sending email through ASP.Net / C# application using gmail as the smtp host. Following is the code I used to send email.

MailMessage mail = new MailMessage();

mail.From = new MailAddress("", "Enquiry");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;

SmtpClient smtp = new SmtpClient("", 587);

//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;


There is no problem with this code and the email will be sent successfully without any error.


When the email is received in the recipient inbox, the "from address" displayed will be of gmail account which is used as the network credential for smtp client. This is because, gmail will over-write the "from address".


You need to follow the below mentioned steps to display the "from address" correctly:

1. Login to your Gmail account.

2. Go to Settings Menu

3. In the Accounts Tab, Click on the link "Add another email address you own"

4. Enter the email address which you want in the "From address" field and click on "Next Step" button.

5. Select Option "Send through Gmail" and click on "Next Step" button.

6. Click on the "Send Verification" button. You will receive an email from Gmail team. This email will have a verification code and a verification link. You need to either enter the verification code or click on the verification link.

7. Enter the Verification code sent by gmail.

8. The account which you require in the "From Address" field will be linked as an alias with your gmail account.

After following the above steps, execute the above given code again. You will see that the "from address" field is not of gmail but the one which is set for the MailMessage.

The above steps also need to be followed when configuring email account for mail clients like Outlook using gmail as the smtp client.

I hope you find this post useful. You can give your inputs in the comments section.

Thanks & Regards,

No comments:

Post a Comment