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.
Like this:
Like Loading...