Sending Mail from a .NET App Using Amazon SES (Simple Email Service)

Amazon’s Simple Email Service (SES) is a great solution for any project which requires bulk emails. the primary advantage of SES is cost, at $0.10 per 1000 emails sent it is between 5-10x cheaper than other alternatives such as SendGrid. There is a downside to the SES service, however and it is that it currently doesn’t provide an SMTP wrapper so whilst SendGrid and others allow you to simple change your SMTP settings, with SES you will have to do a bit more work.

Amazon (AWS) provides a very useful .NET SDK (complete with dll’s for .NET 2.0, 3.5 and 4.0) which you can simply copy into your project and start calling the Amazon functions from a .NET app such as an ASP.NET site. You can download the SDK here.

The below code shows a simple example of how to use the Amazon AWS SDK in .NET to send emails.

Dim listColl As New System.Collections.Generic.List(Of String)
'//TODO - Write a simple loop to add the recipents email addresses to the listColl object.

Dim client As New Amazon.SimpleEmail.AmazonSimpleEmailServiceClient("aws_public_key_here", "aws_private_key_here")

Dim mailObj As New SendEmailRequest
Dim destinationObj As New Destination(listColl)
mailObj.Source = "from@youremail.com"  '//The from email address
mailObj.ReturnPath = "bounce@youremail.com" '//The email address for bounces
mailObj.Destination = destinationObj

'//Create Message
Dim emailSubjectObj As New Amazon.SimpleEmail.Model.Content("This is the Subject")
Dim emailBodyContentObj As New Amazon.SimpleEmail.Model.Content("This is the Body<br /><em>In Html</em>")

Dim emailBodyObj As New Amazon.SimpleEmail.Model.Body()
emailBodyObj.Html = emailBodyContentObj
Dim emailMessageObj As New Message(emailSubjectObj, emailBodyObj)
mailObj.Message = emailMessageObj

Dim response = client.SendEmail(mailObj)

That’s it, there’s really not a lot of heavy lifting to get starting using SES with .NET. the only thing I didn’t show in the code above is the loop for adding email addresses as strings to the generic collection, this loop will vary a lot depending on your exact requirements.
One thing to note above is that you will need to import the namespace Amazon.SimpleEmail.Model

AWS SES is not as full featured as a lot of solutions such as SendGrid, however it does have several useful features out-of-the-box such as the ability to perform email validation:

Dim testEmail As String = "anemail@domain.com"

Dim verRequest As New VerifyEmailAddressRequest()
verRequest.EmailAddress = testEmail
client.VerifyEmailAddress(verRequest)

This should get you going with SES, I will update this page once the service develops.

Sending Bulk Emails in ASP.NET

Just like setting up emailing from a form, in general, is not difficult, neither is sending emails to multiple people at the same time. First, we need to dimension a variable called ‘MyVar’: to hold all the email addresses in a string:

Dim MyVar as String

In inline coding, this would be placed inside the script tag, but outside any Sub or Function.

Next we need to set up the BCC field, grabbing all the emails from a database field called (surprise!) ‘email’:

Dim MySQL as string = "Select email from yourTableName"
Dim MyConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("UrAppString"))
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyVar=""
While objDR.Read()
	MyVar+=objDR("email")& ";"
End While
MyVar=MyVar.substring(0,(MyVar.Length-1))

Continues…

Emailing Form Results in ASP.NET

The task at hand is taking the input from a form, and emailing those results to a desired target. It’s not as hard as one might think. Many of you probably worked with the CDO object in Classic ASP to get this done. If so, you’re much closer to understanding this than you think. Even if you are new to programming, you’re going to be amazed at how simple this really is.

The first thing that’s necessary, of course is the form. For this example, we’re using VB.Net and ASP.Net server controls. Naturally, for the purposes of this tutorial, we’re going to keep it fairly simple, but the same principles apply for a much more expanded form. Here’s a sample of the HTML section for the form:

<Form id="form1" runat="server">
First Name: <asp:TextBox id="txtFname" runat="server" />
Last Name: <asp:TextBox id="txtLname" runat="server" />
Email: <asp:TextBox id="txtEmail" runat="server" />
<asp:Button id="btnEmail" Text="Email Form" onclick="doEmail" runat="server" />
</Form>

The next thing to make sure we have listed on our page is a reference to the correct namespace. For emailing, it’s:

<%@ Import Namespace=”System.Web.Mail” %>

As you probably noticed, there is an ‘onclick’ event referenced for the form’s button, ‘doEmail‘. This is where we’ll take the output of the form and do the actual emailing of the input.

Sub doEmail(Source as Object, E as EventArgs)
	Dim sMsg as String
	sMsg+="Hi there - here's the information I entered in the form." & vbcrlf
	sMsg+="First Name : " & txtFname.Text & vbcrlf
	sMsg+="Last Name : " & txtLname.Text & vbcrlf

	Dim objEmail as New MailMessage
	objEmail.To=txtEmail.text
	objEmail.BCC="JohnnyWhite@jwmason.com" '<--- this would be where you can send it to yourself at the same time.
	objEmail.FROM="me@here.com"

	objEmail.SUBJECT="Here's the subject of the email"
	objEmail.BODY=sMsg
	objEmail.BodyFormat = MailFormat.Text
	SmtpMail.SmtpServer ="mail.Wherever.com"
	SmtpMail.Send(objEmail)
End Sub

In this sub, you’ll notice that the first thing we’re doing is creating a string variable to store our email message. The first part of the message is the opening line, but then you’ll see we’re adding and formatting the specific data from the form, item by item. Naturally, that can be formatted pretty much most anyway you’d like.

Next, we actually reference and instantiate the email object (MailMessage), followed by the essential, basic parts of any email message, the To, From, Subject and Body segments, along with the CC (carbon copy) section. We could also add a BCC section if wanted (Blind Carbon Copy). Remember that string variable we created at the first of the subroutine? We assign it in the Body section. You’ll probably notice that there are no quote marks around sMsg, and that’s BECAUSE it’s a variable. If you wanted to hard code a BODY section here, you’d surround it with double quotes.

Before sending the message, there are two things necessary – assigning a format (Text or HTML), and assigning an SMTP server. If you are using a hosted site, many of them use the format – ‘mail.Wherever.com‘, with ‘Wherever.com’ section being your own domain name. In this case, we’re using a pure text format, but, just as easily, we could have used an HTML format:

objEmail.BodyFormat = MailFormat.HTML

You could then use just about any valid HTML markup tags you wanted inside the BODY section. Of course, you’d need to make sure the person to whom the email is being sent (most likely YOU, in this case) can accept HTML emails correctly. Then, the last line is what really creates and sends the email message:

SmtpMail.Send(objEmail)

Naturally, you’d probably want to add in some validation (ASP.Net validation will be addressed in another Tutorial here), so blank form field results are not sent in the email. So, here you have it in a nutshell – create an input form, along with a subroutine to actuallysend the email, and you’re ready to go. The user just fills in the information for which you asked, clicks the ‘Email Form’ button and the email is on it’s way.

‘What about attachments?’, you may ask. That’s a very good question. In continuing with my ‘It’s not as hard is it may sound’ way of presenting – that’s exactly right – it’s very simple. All you need to do (before the SMTP.Send method, of course is to add this line:

objEmail.Attachments.Add(New MailAttachment(server.mappath(“/yourpath/yourfile.txt”)))

The only catch here is that the file that you’re sending MUST to be ON the file server, and the path you include here needs to be a valid path, either using ‘Server.Mappath’, or an explicit path.

Well – that’s all there is to it…no pain, right?

You might want to check out another Emailing Tutorial on this site, entitled ‘Sending Multiple Emails at Once (Mass Emails)‘ also.