2 September 2014

Email function in Sitecore

Just a quick reminder for those who wants to send an email from Sitecore. There are times where you have to write your own method and this is completely understandable. However, dont forget to check if there is already a method that does it for you... I have seen a SendEmail Method where the SMTP, username, password and port were defined on the item fields. Well for this specific example, you have a method that already send email in sitecore:

Sitecore.MainUtil.SendMail(System.Net.Mail.MailMessage message)

This method is using the System.Net.Mail.SmtpClient to send the email which what most of us will actually implement on custom code. So why not using it... Here is the Method:

  /// 
  /// Sends the mail.
  /// 
  /// The message.
  public static void SendMail(System.Net.Mail.MailMessage message)
  {
   string mailServer = Settings.MailServer;
   System.Net.Mail.SmtpClient smtpClient;
   if (string.IsNullOrEmpty(mailServer))
   {
    smtpClient = new System.Net.Mail.SmtpClient();
   }
   else
   {
    int mailServerPort = Settings.MailServerPort;
    if (mailServerPort > 0)
    {
     smtpClient = new System.Net.Mail.SmtpClient(mailServer, mailServerPort);
    }
    else
    {
     smtpClient = new System.Net.Mail.SmtpClient(mailServer);
    }
   }
   string mailServerUserName = Settings.MailServerUserName;
   if (mailServerUserName.Length > 0)
   {
    string mailServerPassword = Settings.MailServerPassword;
    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(mailServerUserName, mailServerPassword);
    smtpClient.Credentials = credentials;
   }
   smtpClient.Send(message);
  }



So you should be able to use it straight away as per the following:

var myMessage = new MailMessage(from, to, subject, body);
  Sitecore.MainUtil.SendMail(myMessage);


RE-EDITED the post: obviously you need to setup your SMTP in the web.config for this to work:
      < !--  MAIL SERVER
            SMTP server used for sending mails by the Sitecore server
            Is used by MainUtil.SendMail()
            Default value: ""
      -->
      < setting name="MailServer" value="" />
      < !--  MAIL SERVER USER
            If the SMTP server requires login, enter the user name in this setting
      -->
      < setting name="MailServerUserName" value="" />
      < !--  MAIL SERVER PASSWORD
            If the SMTP server requires login, enter the password in this setting
      -->
      < setting name="MailServerPassword" value="" />
      < !--  MAIL SERVER PORT
            If the SMTP server requires a custom port number, enter the value in this setting.
            The default value is: 25
      -->
      < setting name="MailServerPort" value="25" />


I hope that will help...

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Is there a way to check that mail is sent successfully?
    Thanks in Advance.

    ReplyDelete