In my last post, I promised to look at SendRawEmail next. I got busy on other projects so this has taken longer than I originally anticipated it would.
Converting MailMessage into a MemoryStream
public static MemoryStream ConvertMailMessageToMemoryStream(MailMessage message)
{
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
MemoryStream fileStream = new MemoryStream();
ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { fileStream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null);
MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
return fileStream;
}
When we create a request for the SES service, we need to give it a MemoryStream object that contains our mail message. I created a MailMessage object for this, but in order to give this to SES I had to convert it to a MemoryStream. I found the guts of the method above online, and slightly modified it for my own use. I’m not going to talk about it, but you can find it here.
SendRawEmail
public static Boolean SendRawEmail(String from, String to, String Subject, String text = null, String html = null, String replyTo = null, String returnPath = null)
{
AlternateView plainView = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, "text/html");
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(from);
List<String> toAddresses = to.Replace(", ", ",").Split(',').ToList();
foreach (String toAddress in toAddresses)
{
mailMessage.To.Add(new MailAddress(toAddress));
}
//foreach (String ccAddress in ccAddresses)
//{
// mailMessage.CC.Add(new MailAddress(ccAddress));
//}
//foreach (String bccAddress in bccAddresses)
//{
// mailMessage.Bcc.Add(new MailAddress(bccAddress));
//}
mailMessage.Subject = Subject;
mailMessage.SubjectEncoding = Encoding.UTF8;
if (replyTo != null)
{
mailMessage.ReplyTo = new MailAddress(replyTo);
}
if (text != null)
{
mailMessage.AlternateViews.Add(plainView);
}
if (html != null)
{
mailMessage.AlternateViews.Add(htmlView);
}
RawMessage rawMessage = new RawMessage();
using (MemoryStream memoryStream = ConvertMailMessageToMemoryStream(mailMessage))
{
rawMessage.WithData(memoryStream);
}
SendRawEmailRequest request = new SendRawEmailRequest();
request.WithRawMessage(rawMessage);
request.WithDestinations(toAddresses);
request.WithSource(from);
AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AppConfig["AWSAccessKey"], AppConfig["AWSSecretKey"]);
try
{
SendRawEmailResponse response = ses.SendRawEmail(request);
SendRawEmailResult result = response.SendRawEmailResult;
Console.WriteLine("Email sent.");
Console.WriteLine(String.Format("Message ID: {0}", result.MessageId));
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
The above method uses the .NET MailMessage class to create my email message.
Lines 3/4 create our alternative email messages so the email should be visible in whatever mail app is used to retrieve the emails.
Lines 9-13 add the TO addresses to the mail message. Again, I pass in the emails as a string separated by a semi-colon and convert this to a list. The mail message wants each address added as a MailAddress object so a foreach loop steps through the list and adds each address correctly.
Lines 15-23 do the same for CC and BCC address if you wanted to use them. I haven’t in my example, but include the code commented out for you. You’ll also need to add them so you can pass them in when calling the method (Line 1).
Line 25/26 sets the Subject and its encoding and then lines 28-41 add the Reply To address and our alternative views we created earlier (if the String isn’t null).
Line 43 creates our RawMessage object and then lines 45-48 call our method above to convert the MailMessage into a MemoryStream.
We create our request on line 50 and give it our RawMessage on line 51. We also give it our TO addresses and our FROM address on lines 53/54.
We connect to SES on line 56 and then get the response from giving SES our request on lines 60-62 and output to the console the Message ID and a confimation message on lines 64/65.
Other than converting the MailMessage to a MemoryStream this is pretty straight forward. I’ll do my best to help anyone having issues via the comments…
Neil
![]()

Thank you very much for examples.
I tried to add a support of attachments but it seems there are nuances which i dont know.
string file = @”C:\Users\boss\Documents\Visual Studio 2008\Projects\AmazonSES\arrow_left.jpg”;
Attachment data = new Attachment(file, new ContentType( “multipart/mixed” ) );
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
mailMessage.Attachments.Add( data );
It fires exception : [Amazon.SimpleEmail.AmazonSimpleEmailServiceException] = {“Illegal content disposition ‘attachment’ in content type ‘multipart/mixed’.”}
Hi Alex.
Unfortunately, at present Amazon does not support attachments in Simple Email Service (SES). I suspect that this is something they are working on but you’ll have to wait until they update the service and APIs.
See here: https://forums.aws.amazon.com/thread.jspa?threadID=59037&tstart=0
Sorry about that,
Neil
Hi Neil,
I am having account details to send mail using AWS
when i use user id and password i am getting error like
“The security token included in the request is invalid”
I am also having AWSAccessKey and AWSSecretKey when i use this i am getting error like
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details .
My doubt is what we have to provide in web.config file,whether emailaddress and password or encrypted keys.
I am not getting why getting error in my code,
here is my code…
protected void Page_Load(object sender, EventArgs e)
{
AmazonSimpleEmailServiceConfig amConfig = new AmazonSimpleEmailServiceConfig();
amConfig.UseSecureStringForAwsSecretKey = false;
AmazonSimpleEmailServiceClient amzClient = new AmazonSimpleEmailServiceClient(ConfigurationManager.AppSettings["AWSAccessKey"].ToString(), ConfigurationManager.AppSettings["AWSSecretKey"].ToString(),amConfig);
ArrayList to = new ArrayList();
//ADD AS TO 50 emails per one sending method//////////////////////
to.Add(“rehan225@gmail.com”);
to.Add(“developer1089@hotmail.com”);
//ADD AS TO 50 emails per one sending method/////////////////////
Destination dest = new Destination();
dest.WithBccAddresses((string[])to.ToArray(typeof(string)));
string body = “INSERT HTML BODY HERE”;
string subject = “INSERT EMAIL SUBJECT HERE”;
Body bdy = new Body();
bdy.Html = new Amazon.SimpleEmail.Model.Content(body);
Amazon.SimpleEmail.Model.Content title = new Amazon.SimpleEmail.Model.Content(subject);
Message message = new Message(title, bdy);
//VerifyEmailAddressRequest veaRequest = new VerifyEmailAddressRequest();
//veaRequest.EmailAddress =”developer1088@hotmail.com”;
//VerifyEmailAddressResponse veaResponse = amzClient.VerifyEmailAddress(veaRequest);
SendEmailRequest ser = new SendEmailRequest(“developer1089@hotmail.com”, dest, message);
SendEmailResponse seResponse = amzClient.SendEmail(ser);
SendEmailResult seResult = seResponse.SendEmailResult;
}
Hi Rehan,
I have used your exact code above, but with my own email addresses instead and it worked.
I would check that you AWS Keys are correct and the right one is associated to the correct key etc.
It is certainly a security issue. The only other thing I can think of is that you are not verifying the email address (I had to when I did my code, but that might have changed), but you had code in there for that so I guess you have.
Step through the code and check everything is working…. which line does the error occur on?
Neil
Hello Neil!
Amazon SES dll has a big problem. It does not work on hosting servers which requires application run under medium trust level (www.rackspacecloud.com). So I tried to rewrite
php code which realize API directly by means GET/POST http requests.
It is was problem to make correct GET request by means HttpWebRequest now it works but I can not make correct POST request and can not find where is problem.
The same code on PHP works for GET and POST.
Here is my code .
https://forums.aws.amazon.com/thread.jspa?threadID=60986&tstart=0
P.S.
I would like to treat a cup of coffee. If you have paypal account or moneybooker account say me.
Thank you
After contacting Alex via his email address, I was able to help him out. I posted the answer to the link he provided.
Neil, I have a need where I need to either get notified than an email has arrived or simply go through the inbox and retrieve the from address and the attachment. Any hints or a blog would tremendously help.
Thanks.
Hi Frank,
You mention an inbox, but not what inbox you mean. The Amazon SES service doesn’t have an inbox, its just meant as a Mail Server for sending mails through. In order to receive replies, you’d need a mail account elsewhere to be set up.
Depending on the mail account your using, it should be fairly simple to do what you asked say in GMail etc.
Have I understood you correctly?
Hi!
My MainMessage with LinkedResources is failing while using above code. As per my understanding it is limitation while using .NET and SNS https://forums.aws.amazon.com/thread.jspa?messageID=272523#272523
Can you please advice?
Regards
Prasad
Now, AWS SES supports sending attachments can someone post the correct c# code for sending attachments. More number of people are getting ‘illegal content disposition’ error.
I have a simple question: Should I use Amazon APIs in order to send mails? I want to host my site on EC2 and I don’t want to change anything my code include send mails code. is it possible? can I use my old code that uses SMTP host to send mails with EC2?
To send mails, you will need some sort of SMTP installation. If you are keeping the old server that your old code uses to send emails then it will work. If, however, you losing the SMTP server then you will need to set one up or use Amazon’s AWS APIs.
If you are running a Windows instance it can easily be configured to send mail (i.e. set up as SMTP server). Googling will provide the info you require (and also for linux if you are using a different OS).
The AWS APIs are useful because it is one less thing to worry about, but you will have to pay…
Okay, Now I understand that my old code that uses SMTP server will work only if I used an external email service provide, while to use amazon SES then I must use amazon API’s and I must change my code?
I though that using amazon SES is a sample task, and it only needs from me to change the SMTP server name in my code (configuration file) to new one provide by amazon!
Amazon make it hard for people to move the their service, becasue moveing to amazon involve a code changes.
Can you advice me about the following:
I have a web site that users register for news letter, the number of users is huge (some thing like 500K or more), and there is at least one mail message will be send to all users every day.
So which is better: Amazon SES or external services like http://www.massmailservers.net/services/high-volume-bulk-email-hosting/
Thanks Neil for your help
Your old code will work if that SMTP server still exists. If you are only using the mailserver for SMTP, you can, as I said in my last reply, create your own SMTP server on the servers. Then you have no need to pay for extra service.
Amazon SES charges per data transfer, so its difficult to say which is better compared to the one you suggested. I would probably favour SES as it keeps all costs under one service, but you really need to decide for yourself.
It really isn’t hard to use SES, as my code shows.
HI Neil,
we are developed one project in Microsoft asp.net with c-sharp for sending news letters to my customers. Present i aim using port25 we are sending mails but it is very high cost. that’s why i am choose Amazon SES
I am new user of this Amazon SES, i have smpt username and password also but my main problem is how to integrate already existed application. Can you please guide me.
Thanks.
Hi developer1069,
My code examples should pretty much be all you need, although it has been a long time since I tried running them and I can’t say if they still work (Amazon may have altered the APIs).
If you are stuck with a particular problem, I can attempt to assist you…
Neil
Hi Neil, Thanks for your reply
My mail Problem is Integration.
1) i am download s/w from Amazan ‘AWS SDK’ and also installed in my PC when i am clicking AddAccount button on AWS Explore it will ask AccessKey, SecretKey and Account Number. I have AccessKey and secretkey but i don’t have Account Number. What is Account Number?
2) how to attach already existing Database to AWS Explore. I am using Microsoft Sql Server as back end.
3) how to get report like sent,Mail Bounce and Forward Counts or details.
1) Account number is you AWS Account number and is shown here: https://aws-portal.amazon.com/gp/aws/manageYourAccount – beneath Sign Out on right hand side.
2) If your code uses MS SQL Server, then you don’t need AWS Explorer. AWS Explorer is only for using connecting to AWS services. You could use one of their databases, but you’d need to search for that yourself.
3) I don’t believe SES will provide these functions, at least it didn’t when I wrote this blog article. If you need finer control, you’d need to use a dedicated SMTP server of your own.
Hi Neil,
while sending a mail using above code. i got below error.
‘The security token included in the request is invalid.’
can you please give any suggestion.