Ready to send email in Amazon SES? Let’s Go!

First, consult with AWS and get your credentials:

http://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-credentials.html
and
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-net.html

Secondly, let’s make a more easily updatable emailSettings section (encrypt it later, see here if you need help):

  <appSettings>
    <add key="MailFrom" value="donotreply@youremaildomain.com"/>
    <add key="MailTo" value="whoareyousendingto@theiremaildomain.com"/>
    <add key="MailHost" value="	email-smtp.youramazonseshost.com"/>
    <add key="MailPort" value="587"/>
    <add key="MailServerUserName" value="awsSESusername"/>
    <add key="MailServerPassword" value="awsSESpassword"/>
  </appSettings>

Then, include the reference:

	using System.Net.Mail;		

Finally, write your method:

	public static void sendEmail(string to, string from, string subject, string body)
	{
		try
		{
			// Initialize client and message
			using (SmtpClient mailclient = new SmtpClient(ConfigurationManager.AppSettings["MailHost"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"])))
			{
				// Create message
				mailclient.UseDefaultCredentials = false;
				mailclient.EnableSsl = true;
				mailclient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailServerUserName"].ToString(), ConfigurationManager.AppSettings["MailServerPassword"].ToString());
				MailMessage message = new MailMessage(from, to);
				message.Subject = subject;
				message.Body = body;
				message.IsBodyHtml = true;
				mailclient.Send(message);
			}
		}
		catch (SmtpException ex)
		{                
			// Service was not available to send message keep trying
			if (ex.StatusCode.Equals(SmtpStatusCode.ServiceNotAvailable))
			{
				sendEmail(to, from, subject, body);
			}
		}
	}

Great! Now you can call it and send an email

string htmlBody = "<b>Hi! It's my message</b>";
sendEmail(ConfigurationManager.AppSettings["MailTo"].ToString(), ConfigurationManager.AppSettings["MailFrom"].ToString(), "Your Email Subject", htmlBody); 

You can always put whoever and whatever when you call the method using To, From, Subject and Body.

Enjoy! Questions are welcome.

Advertisements

How to deal with: WARN An invalid character was found in the mail header: ‘,’ in Sitecore

If you are using Web Forms for Marketers in Sitecore then you may have an occasion where the email addresses that are being used to send messages to get updated by someone…then all of a sudden you start getting errors…then all of a sudden your phone starts ringing off the hook, right?

So in the Sitecore logs you will see something similar to:

 868 13:12:53 WARN An invalid character was found in the mail header: ','.
Exception: System.FormatException
Message: An invalid character was found in the mail header: ','.
Source: System
 at System.Net.Mail.DotAtomReader.ReadReverse(String data, Int32 index)
 at System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32& index)
 at System.Net.Mail.MailAddressParser.ParseAddress(String data, Boolean expectMultipleAddresses, Int32& index)
 at System.Net.Mail.MailAddressParser.ParseMultipleAddresses(String data)
 at System.Net.Mail.MailAddressCollection.ParseValue(String addresses)
 at System.Net.Mail.Message..ctor(String from, String to)
 at System.Net.Mail.MailMessage..ctor(String from, String to)
 at System.Net.Mail.MailMessage..ctor(String from, String to, String subject, String body)
 at Sitecore.Form.Core.Pipelines.ProcessMessage.ProcessMessage.GetMail(ProcessMessageArgs args)
 at (Object , Object[] )
 at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
 at Sitecore.Form.Core.Submit.SubmitActionManager.ExecuteSaving(ID formID, ControlResult[] list, ActionDefinition[] actions, Boolean simpleAdapt, ID sessionID)

Huh? OK, so let’s go look at the Web Form Send Email action in question:

ss1wffm

Nothing looks odd at first…until upon further research: I discovered after some reading about mail headers that the last entry of the recipients (To, CC, BCC) cannot accept a separator delimiter as a character on the end. You’ll also notice in outlook and other email clients that the behavior is the same.

The fix? remove the last character and save/republish your form. Problem solved!

ss2wffm

Hope this helps. Questions are welcome!

Programmatically Send An Email Message With An Html Body (C#)

I have used the following snippet many times in the past. I would recommend validating your string values if the values are dynamic. I would also recommend placing your email attempt in a try/catch so you will not break your web application if there is some kind of issue on the email server itself. Anyway, hope this helps.

using System.Net.Mail;

// server settings
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "exchangeserver.yourdomain.com";

// declasre mail message
MailMessage mm = new MailMessage();

// from
mm.From = new MailAddress("donotreply@yourdomain.com");

// to
string toemail = "";
toemail = "persontosendto@yourdomain.com";
mm.To.Add(new MailAddress(toemail));

// cc
string toemailcc = "";
toemailcc = "another_person@yourdomain.com";
mm.CC.Add(new MailAddress(toemailcc));

// subject
mm.Subject = "The All Important Subject";

// body
string message = "";
message = "This is the all important email body message. &lt;br /&gt;&lt;br /&gt;";
message = message + "Sincerely yours, &lt;br /&gt;&lt;br /&gt;";
mm.Body = message;
mm.IsBodyHtml = true;

// send the message
client.Send(mm);