January 28, 2015

Sending EMail Using SMTP in .NET

Here was the old way of sending email using an SMTP email service
using System.Web.Mail; // OLD WAY
...
private void SendEMail()
{
    Common.ResponseHelper rh = new Common.ResponseHelper();
    MailMessage email = new MailMessage();
    email.To = _TargetEMail;
    email.Cc = _CcTargetEMail;
    email.From = _txtFromEMail;
    email.Subject = "EMail Subject";
    email.Body = _txtComments;
    email.Priority = MailPriority.Normal;
    email.BodyFormat = MailFormat.Text; 
    SmtpMail.SmtpServer = "localhost";

    try
    {
        SmtpMail.Send(email);
        rh.WriteComment("Email has been sent successfully");
        Response.Redirect("emailsent.aspx"); // Redirect to an email sent web-page
    }
    catch (Exception ex)
    {
        rh.WriteComment("Send failure: " + ex.ToString());
    }
}
Had to convert this to using the new form
using System.Net.Mail;
...
private void TrySendEMail()
{
    Common.ResponseHelper rh = new Common.ResponseHelper();
    try
    {
        using (MailMessage email = new MailMessage())
        {               
            email.To.Add(_targetEMail);
            email.CC.Add(_ccTargetEMail);
            email.From = new MailAddress(_fromEMailAddress);

            email.Subject = "EMail Subject";
            email.Body = _txtComments;
            email.Priority = MailPriority.Normal;
            email.IsBodyHtml = false;

            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = "localhost";
                smtp.Port = 25;
                smtp.EnableSsl = false;
                NetworkCredential networkCred = new NetworkCredential(
                   _fromEMailAddress, UnmashPassword("oX9iioW7eTX5LS7T"));
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = networkCred;

                smtp.Send(email);
                rh.WriteComment("Email has been sent successfully");
                Response.Redirect("emailsent.aspx");
            }                
        }
    }
    catch (Exception exc)
    {
        rh.WriteComment("Send failure: " + exc.ToString());
    }
}
Had some problems sending email to my googlemail account:
  1. Had to ensure that the email sender address was one that existed
  2. Had to ensure that the "MailMessage.From" property matched the EMail address used for the "NetworkCredentials" constructor.
Without these changes Google rejected my emails (silently).

No comments: