Pages

Saturday, July 7, 2012

Sending email through Gmail SMTP server with C#


I've had some problems sending emails from my gmail account too, which were due to several of the aforementioned situations. Here's a summary of how I got it working, and keeping it flexible at the same time:
  • First of all setup your GMail account:
    • Enable IMAP and assert the right maximum number of messages (you can do so here)
    • Make sure your password is at least 7 characters and is strong (according to Google)
    • Make sure you don't have to enter a captcha code first. You can do so by sending a test email from your browser.
  • Make changes in web.config (or app.config, I haven't tried that yet but I assume it's just as easy to make it work in a windows application):
<configuration>
    <appSettings>
        <add key="EnableSSLOnMail" value="True"/>   
    </appSettings>

    <!-- other settings --> 

    ...

    <!-- system.net settings -->
    <system.net>
        <mailSettings>
            <smtp from="yourusername@gmail.com" deliveryMethod="Network">
                <network 
                    defaultCredentials="false" 
                    host="smtp.gmail.com" 
                    port="587" 
                    password="stR0ngPassW0rd" 
                    userName="yourusername@gmail.com"
                    />
                <!-- When using .Net 4.0 (or later) add attribute: EnableSSL="True" and you're all set-->
            </smtp>
        </mailSettings>
    </system.net>
</configuration>

Add a Class to your project:
using System.Net.Mail; public class SSLMail { public static void SendMail(System.Web.UI.WebControls.MailMessageEventArgs e) { GetSmtpClient.Send(e.Message); //Since the message is sent here, set cancel=true so the original SmtpClient will not try to send the message too: e.Cancel = true; } public static void SendMail(MailMessage Msg) { GetSmtpClient.Send(Msg); } public static SmtpClient GetSmtpClient() { Net.Mail.SmtpClient smtp = new Net.Mail.SmtpClient(); //Read EnableSSL setting from web.config smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings("EnableSSLOnMail")); return smtp; } }


And now whenever you want to send emails all you need to do is call SSLMail.SendMail:
e.g. in a Page with a PasswordRecovery control:
partial class RecoverPassword : System.Web.UI.Page { protected void // ERROR: Handles clauses are not supported in C# RecoverPwd_SendingMail(object sender, System.Web.UI.WebControls.MailMessageEventArgs e) { e.Message.Bcc.Add("webmaster@example.com"); SSLMail.SendMail(e); } }


Or anywhere in your code you can call:
SSLMail.SendMail(new system.Net.Mail.MailMessage("from@from.com", "to@to.com", "Subject", "Body"))

No comments:

Post a Comment