Send raw bulkmail using aws ses ApI interface(Empty required header 'To'.) - c#

Hi I am trying to send bulkmail with attachment using amazon ses. I can able to send mails with attachment but my to-mails are appearing for all the users that I have send. I am trying to add those destination mails in bcc fields but it is throwing an error Empty required header 'To'.
This is what I've already tried:
private static BodyBuilder GetMessageBody()
{
var body = new BodyBuilder()
{
HtmlBody = #"<p>Amazon SES Test body</p>",
TextBody = "Amazon SES Test body",
};
body.Attachments.Add(#"G:\me.jpg");
return body;
}
private static MimeMessage GetMessage()
{
var message = new MimeMessage();
List<string> to = new List<string>(50);
to.Add("xxxxxx#gmail.com");
to.Add("xxxxxx#gmail.com");
message.From.Add(new MailboxAddress(ConfigurationManager.AppSettings["senderaddress"], ConfigurationManager.AppSettings["senderaddress"]));
for (int i = 0; i < to.Count; i++)
{
message.Bcc.Add(new MailboxAddress(string.Empty,to[i]));
//message.To.Add(new MailboxAddress(string.Empty, "xxxxx#gmail.com"));
//message.To.Add(new MailboxAddress(string.Empty, "xxxxxx#gmail.com"));
}
message.Subject = "Amazon SES Test";
message.Body = GetMessageBody().ToMessageBody();
return message;
}
private static MemoryStream GetMessageStream()
{
var stream = new MemoryStream();
GetMessage().WriteTo(stream);
return stream;
}
private void SendEmails()
{
var credentals = new BasicAWSCredentials(ConfigurationManager.AppSettings["AccessKey"], ConfigurationManager.AppSettings["SecretAccessKey"]);
using (var client = new AmazonSimpleEmailServiceClient(credentals, RegionEndpoint.USEast1))
{
var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage(GetMessageStream()) };
try
{
var response = client.SendRawEmail(sendRequest);
}
catch (Exception e)
{
}
}
}

You need at least 1 email address in to 'To' field. Perhaps send the email to yourself and add the others as a BCC.

Instead of using the BCC header to send out bulk mails, IMHO you should send one email with a clear "to" header to each of the recipients. So instead looping through recipients and adding them to BCC you should rather create and send a message there.

Related

LinkedResource fails in MailMessage with CC recipients, succeeds otherwise

I am developing a Windows Background Service with .NET and C#. It periodically queries a REST API and sends emails if certain conditions are met. Sometimes the data returned from the API will have image files and sometimes not. When image files are returned, the service embeds them into the email body before sending. I'm embedding the image file in four steps:
Download the image as a byte[]
Convert byte[] to MemoryStream
pass the stream to a new LinkedResource
Add the linked resource to the AlternateView for the MailMessage
This works if the message has a single "To" recipient and no CC or BCC recipients. The image displays correctly in the body of the email. The weird problem I'm having is that if I add multiple recipients in To, CC or BCC, the image fails to display in the email body. This problem seems to be limited to Outlook. I did a test with two recipients, one internal to the organization and one Gmail account. The image displayed correctly in Gmail but was broken in Outlook.
Here is the snippet of code where the service builds the LinkedResource and sends the email.
htmlBody = htmlBody.Replace("{incident_time}", incident.IncidentTime)
.Replace("{incident_type}", incident.IncidentType)
.Replace("{incident_location}", incident.IncidentLocation)
.Replace("{reporting_agency}", incident.ReportingAgency)
.Replace("{severity}", incident.Severity)
.Replace("{details}", incident.Details);
// embed attached images
var attachmentsResult = await arcGisRestClient.QueryAttachmentsAsync(
incidentSublayerUrl,
tokenResponse.Token,
objectId: incident.ObjectId);
IList<LinkedResource> linkedResources = new List<LinkedResource>();
if (!string.IsNullOrEmpty(attachmentsResult))
{
var attachmentsObj = JObject.Parse(attachmentsResult);
var attachments = FeatureAttachmentConverter.FromJObject(attachmentsObj);
// if attachments > 0
if (attachments.Count > 0)
{
string imgHtml = "";
foreach (var attachment in attachments)
{
string attachmentUrl = $"{incidentSublayerUrl}/{attachment.ParentObjectId}/attachments/{attachment.Id}?token={tokenResponse.Token}";
WebClient webClient = new WebClient();
byte[] bytes = webClient.DownloadData(attachmentUrl);
MemoryStream stream = new MemoryStream(bytes);
LinkedResource linkedResource = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
imgHtml += #"<img src='cid:" + linkedResource.ContentId + #"' width='450'/>";
linkedResources.Add(linkedResource);
}
htmlBody = htmlBody.Replace("{attachments}", imgHtml);
}
else
{
htmlBody = htmlBody.Replace("{attachments}", "");
}
}
AlternateView htmlAlternate = AlternateView.CreateAlternateViewFromString(htmlBody, new ContentType(MediaTypeNames.Text.Html));
foreach (var lr in linkedResources)
{
htmlAlternate.LinkedResources.Add(lr);
}
// create email
MailMessage message = new MailMessage
{
Subject = "TEST Incident Notification",
};
message.AlternateViews.Add(htmlAlternate);
string[] emailToAddresses = _config.GetSection("EmailNotificationTo").Get<string[]>();
message.To.Add(string.Join(',', emailToAddresses));
string[] emailCcAddresses = _config.GetSection("EmailNotificationCc").Get<string[]>();
message.CC.Add(string.Join(',', emailCcAddresses));
message.From = new MailAddress(_config["EmailNotificationFrom"]);
// send email
SmtpClient smtpClient = new SmtpClient("mail.domain.org", 25);
using (smtpClient)
{
smtpClient.Send(message);
logger.Info($"Email notification sent; objectid: {incident.ObjectId}");
}
Could this be an issue with our internal STMP server or Outlook settings rather than a problem with the above code?

Converting SMTP Sendgrid to Sendgrid API

Currently replacing the old SMTP Sendgrid to API Sendgrid and I noticed that there are some differences in their code.But I was thinking that since they are both sendgrid it will just work. What I did is to add this SendGridClient.SendEmailAsync(Message); in the end. But it says
cannot convert from system.net.mail.mailmessage to sendgrid.helpers.mail.sendgridmessage
Is this the correct way of converting it?
Below is the code.
try
{
string SendGridKey = ConfigurationManager.AppSettings["SendGridKey"];
var SendGridClient = new SendGridClient(SendGridKey);
using (MailMessage MessageContent = new MailMessage())
{
MessageContent.From = new MailAddress(From);
MessageContent.To.Add(new MailAddress(To));
MessageContent.Subject = Subject;
MessageContent.Body = (TextBody);
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView Alternate = AlternateView.CreateAlternateViewFromString(HtmlBody, mimeType);
Message.AlternateViews.Add(Alternate);
if (AttachedFileName == true)
{
Attachment AttachedFile = new Attachment(HttpRuntime.AppDomainAppPath + "Path\\" + AttachedFileName);
MessageContent.Attachments.Add(AttachedFile);
}
//using (SmtpClient Client = new SmtpClient())
//{
// Client.EnableSsl = true;
// Client.Send(MessageContent);
//}
SendGridClient.SendEmailAsync(Message);
}
return;
}
For sending mail using SendGrid API, you need to create com.sendgrid.Request object. Adding code for java:
import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;
Email from = new Email("<FROM_EMAIL>");
String subject = "<SUBJECCT>";
Email to = new Email("<TO_EMAIL>");
Content content = new Content("text/plain", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(SendGridKey);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
log.info("Main sent successfully");
} catch (IOException ex) {
log.info("Error while sending mail: {}", ex.toString());
}

Sending email with attachments using Amazon AWS SMTP

I'm trying to send a email using amazon WS SMTP, is sending with success but i never receive the email. When i send it without attachment i receive it with success.
Here's my code
// Create an SMTP client with the specified host name and port.
using (SmtpClient client = new SmtpClient(ssHost, ssPort))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(ssSMTP_Username, ssSMTP_Password);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
MailMessage message = new MailMessage();
try
{
//creates a messages with the all data
message.From = new MailAddress(ssFrom, ssFromName);
//message.To.Add(ssTo);
//To
List<String> toAddresses = ssTo.Split(',').ToList();
foreach (String toAddress in toAddresses)
{
message.To.Add(new MailAddress(toAddress));
}
//cc
List<String> ccAddresses = ssCC.Split(',').Where(y => y != "").ToList();
foreach (String ccAddress in ccAddresses)
{
message.CC.Add(new MailAddress(ccAddress));
}
//bcc
List<String> BccAddresses = ssBcc.Split(',').Where(y => y != "").ToList();
foreach (String ccAddress in ccAddresses)
{
message.Bcc.Add(new MailAddress(ccAddress));
}
//replyTo
if (ssReplyTo != null)
{
message.ReplyToList.Add(new MailAddress(ssReplyTo));
}
//email
message.Subject = ssSubject;
message.Body = ssBody;
message.IsBodyHtml = true;
//Attachment
foreach (RCAttachmentRecord attchmentRec in ssAttachmenstList){
System.IO.MemoryStream ms = new System.IO.MemoryStream(attchmentRec.ssSTAttachment.ssBinary);
Attachment attach = new Attachment(ms, attchmentRec.ssSTAttachment.ssFilename);
message.Attachments.Add(attach);
ssErrorMessage = ssErrorMessage + "||" + attchmentRec.ssSTAttachment.ssFilename+"lenght:"+attchmentRec.ssSTAttachment.ssBinary.Length;
}
client.Send(message);
}
source: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-net.html
I think your problem probably is that you are not adding your attachments correctly to your message.
I was successful sending a single message with an attachment. I started with the code that was taken directly from your source link above. I then added the code from another SO article about the missing content type problem.
The attachment is a Word Document Lebowski.docx from my Documents folder. I suggest you create a similar simple Word document and run the following code to verify you can send a simple attachment in a single email.
The following code worked successfully for me:
namespace SESTest
{
using System;
using System.Net.Mail;
namespace AmazonSESSample
{
class Program
{
static void Main(string[] args)
{
const String FROM = "from-email"; // Replace with your "From" address. This address must be verified.
const String TO = "to-email"; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
const String SUBJECT = "Amazon SES test (SMTP interface accessed using C#)";
const String BODY = "This email and attachment was sent through the Amazon SES SMTP interface by using C#.";
// Supply your SMTP credentials below. Note that your SMTP credentials are different from your AWS credentials.
const String SMTP_USERNAME = "user-creds"; // Replace with your SMTP username.
const String SMTP_PASSWORD = "password"; // Replace with your SMTP password.
// Amazon SES SMTP host name.
const String HOST = "your-region.amazonaws.com";
// The port you will connect to on the Amazon SES SMTP endpoint. We are choosing port 587 because we will use
// STARTTLS to encrypt the connection.
const int PORT = 2587;
// Create an SMTP client with the specified host name and port.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
try
{
Console.WriteLine("Attempting to send an email through the Amazon SES SMTP interface...");
var mailMessage = new MailMessage()
{
Body = BODY,
Subject = SUBJECT,
From = new MailAddress(FROM)
};
mailMessage.To.Add(new MailAddress(TO));
//REMOVE THIS CODE
//System.IO.MemoryStream ms = new System.IO.MemoryStream(attchmentRec.ssSTAttachment.ssBinary);
//Attachment attach = new Attachment(ms, attchmentRec.ssSTAttachment.ssFilename);
//mailMessage.Attachments.Add(attach);
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
contentType.Name = "Lebowski.docx";
mailMessage.Attachments.Add(new Attachment("C:\\users\\luis\\Documents\\Lebowski.docx", contentType));
client.Send(mailMessage);
Console.WriteLine("Email sent!");
}
catch (Exception ex)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + ex.Message);
}
}
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
}
Once you prove you can send an email with one attachment from your account, then you can start working on how to get the binaries from your ssAttachmentsList into an your emails and the correct content type assigned to each. But you didn't provide enough code or context for me to determine that at this time. Im hoping this code will help you get over your attachment issue.

how to convert non-mime message to mime mail message in c#

i got a mail message which is not a MIME message
can not get Content-Type
can not get attachment
how to convert this message into MIME message
foreach (AE.Net.Mail.Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
string sender = m.From.Address;
ICollection<Attachment> cc = m.Attachments;
foreach (Attachment aa in cc)
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
}
Update
does this disposition work for non-mime message?
public string GetDisposition()
{
return this["Content-Disposition"]["boundary"];
}
string disposition = Headers.GetDisposition();
if (!string.IsNullOrEmpty(disposition))
{
//else this is a multipart Mime Message
using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
ParseMime(subreader, disposition);
}
else
{
//SetBody((line + Environment.NewLine + reader.ReadToEnd()).Trim());
}
can i send non-mime email to myself ? so that i can receive mime format email?
when i try this, i can not email to myself
ImapClient imap = new ImapClient("imap.gmail.com", "hello#gmail.com", "pwd", ImapClient.AuthMethods.Login, 993, true, true);
//imap.Connect("imap.gmail.com", 993, true, true);
imap.SelectMailbox("INBOX");
//MailMessage[] mm = imap.GetMessages(imap.GetMessageCount() - 1, imap.GetMessageCount() - 10, false, false);
AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage>[] messages = imap.SearchMessages(SearchCondition.Unseen(), false);
// Run through each message:
foreach (AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage> message in messages)
{
AE.Net.Mail.MailMessage mm = message.Value;
//create the mail message
//var mail = new MailMessage();
var mail = new System.Net.Mail.MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com", "demo");
mail.To.Add("hello#gmail.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
//var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
//var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
ICollection<AE.Net.Mail.Attachment> cc = mm.AlternateViews;
foreach (AE.Net.Mail.Attachment aa in cc)
{
try
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//mail.AlternateViews.Add(b);
}
var plainView = AlternateView.CreateAlternateViewFromString(mm.Raw, null, "text/plain");
mail.AlternateViews.Add(plainView);
//send the message
var smtp = new SmtpClient("smtp.gmail.com", 587); //specify the mail server address
smtp.Credentials = new System.Net.NetworkCredential("hello#gmail.com", "pwd");
smtp.EnableSsl = true;
smtp.Send(mail);
smtp = null;
mail.Dispose();
You can use this sample:
//create the mail message
var mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);

Send Attachments with Amazon-SES

I'm searching for an working C# example to send attachments with Amazon-SES.
After reading that Amazon-SES now supports sending attachments I was searching for an C# example but was unable to find one.
I think that using AWS SDK for .NET and MimeKit is very easy and clean solution. You can send e-mails with attachments via SES API (instead of SMTP).
You can write MimeMessage directly to MemoryStream and then use it with SES SendRawEmail:
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using Amazon;
using Amazon.Runtime;
using MimeKit;
private static BodyBuilder GetMessageBody()
{
var body = new BodyBuilder()
{
HtmlBody = #"<p>Amazon SES Test body</p>",
TextBody = "Amazon SES Test body",
};
body.Attachments.Add(#"c:\attachment.txt");
return body;
}
private static MimeMessage GetMessage()
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Foo Bar", "foo#bar.com"));
message.To.Add(new MailboxAddress(string.Empty, "foobar#example.com"));
message.Subject = "Amazon SES Test";
message.Body = GetMessageBody().ToMessageBody();
return message;
}
private static MemoryStream GetMessageStream()
{
var stream = new MemoryStream();
GetMessage().WriteTo(stream);
return stream;
}
private void SendEmails()
{
var credentals = new BasicAWSCredentials("<aws-access-key>", "<aws-secret-key>");
using (var client = new AmazonSimpleEmailServiceClient(credentals, RegionEndpoint.EUWest1))
{
var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage(GetMessageStream()) };
try
{
var response = client.SendRawEmail(sendRequest);
Console.WriteLine("The email was sent successfully.");
}
catch (Exception e)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + e.Message);
}
}
}
public Boolean SendRawEmail(String from, String to, String cc, String Subject, String text, String html, String replyTo, string attachPath)
{
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));
}
List<String> ccAddresses = cc.Replace(", ", ",").Split(',').Where(y => y != "").ToList();
foreach (String ccAddress in ccAddresses)
{
mailMessage.CC.Add(new MailAddress(ccAddress));
}
mailMessage.Subject = Subject;
mailMessage.SubjectEncoding = Encoding.UTF8;
if (replyTo != null)
{
mailMessage.ReplyToList.Add(new MailAddress(replyTo));
}
if (text != null)
{
mailMessage.AlternateViews.Add(plainView);
}
if (html != null)
{
mailMessage.AlternateViews.Add(htmlView);
}
if (attachPath.Trim() != "")
{
if (System.IO.File.Exists(attachPath))
{
System.Net.Mail.Attachment objAttach = new System.Net.Mail.Attachment(attachPath);
objAttach.ContentType = new ContentType("application/octet-stream");
System.Net.Mime.ContentDisposition disposition = objAttach.ContentDisposition;
disposition.DispositionType = "attachment";
disposition.CreationDate = System.IO.File.GetCreationTime(attachPath);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachPath);
disposition.ReadDate = System.IO.File.GetLastAccessTime(attachPath);
mailMessage.Attachments.Add(objAttach);
}
}
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(ConfigurationManager.AppSettings.Get("AccessKeyId"), ConfigurationManager.AppSettings.Get("SecretKeyId"));
try
{
SendRawEmailResponse response = ses.SendRawEmail(request);
SendRawEmailResult result = response.SendRawEmailResult;
return true;
}
catch (AmazonSimpleEmailServiceException ex)
{
return false;
}
}
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;
}
Found that here
Update: A method signature has changed in .NET 4.5, which breaks the above:
Getting System.Net.Mail.MailMessage as a MemoryStream in .NET 4.5 beta
This is a very simple implementation using MimeKit
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using MimeKit;
using System.IO;
namespace SendEmailWithAttachments
{
class Program
{
static void Main(string[] args)
{
//Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
using (var messageStream = new MemoryStream())
{
var message = new MimeMessage();
var builder = new BodyBuilder() { TextBody = "Hello World" };
message.From.Add(new MailboxAddress("FROMADDRESS#TEST.COM"));
message.To.Add(new MailboxAddress("TOADDRESS#TEST.COM"));
message.Subject = "Hello World";
//I'm using the stream method, but you don't have to.
using (FileStream stream = File.Open(#"Attachment1.pdf", FileMode.Open)) builder.Attachments.Add("Attachment1.pdf", stream);
using (FileStream stream = File.Open(#"Attachment2.pdf", FileMode.Open)) builder.Attachments.Add("Attachment2.pdf", stream);
message.Body = builder.ToMessageBody();
message.WriteTo(messageStream);
var request = new SendRawEmailRequest()
{
RawMessage = new RawMessage() { Data = messageStream }
};
client.SendRawEmail(request);
}
}
}
}
I have the code in my repository https://github.com/gianluis90/amazon-send-email
You can setup IIS SMTP to relay through SES as well.
You need to install stunnel and set it up
Then you can just set the IIS SMTP Smart Host and some other options and it will relay your email through SES.
Instructions from above linked gist:
Instructions taken from Amazon's docs and modified as necessary.
1. Install stunnel:
Download from stunnel's download page
Run installer w/ default options, create self signed cert by answering questions
Open the c:\program files (x86)\stunnel\stunnel.conf file in notepad
Clear all the server configs (under Example SSL server mode services section, won't have a client = yes line)
Create a new client config:
[smtp-tls-wrapper]
accept = 127.0.0.1:2525
client = yes
connect = email-smtp.us-east-1.amazonaws.com:465
Start stunnel.exe and ensure no errors are reported (you will get a little systray icon)
If it succeeds you can optionally install as a service, by running stunnel.exe -install at command line (note this installs the service but doesn't start it, so start it)
Test the connection, at cmd line run telnet localhost 2525 and you should see an SMTP response from Amazon's server (if telnet isn't installed, add the feature in Server Manager / Features / Add Feature)
2. Configure IIS SMTP
Set Smart Host as [127.0.0.1] (include the brackets)
In the Outbound Connections section, set outgoing port to 2525 (like the stunnel.conf file)
In the Outbound Security section, set authentication information to your Amazon SMTP credentials, set it to basic authentication (NOTE: DO NOT CHECK THE TLS CHECKBOX)
I'm not sure if this is what you are looking for, but it's the only resource I've been able to find on the subject. I would love a better answer to this question, too.
http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/
It states how to use it, but is very cryptic, at least to me.
Any better guides out there?
I also need help with this, but so far I've found you need to send a multipart MIME message, with the attachment encoded in base64.
I think you need to follow the instructions on this link. Amazon doesn't let you add attachments or other more complicated message types (iCalendar events). Essentially you need to handcraft the message body by string building and manipulation.
Currently I do this for iCalendar format emails on a legacy system. It's a bit of a pain in the ass, but if you read RFC 2822, it tells you pretty clearly what the format is. Special things to pay attention to:
Base64 encoding of the data
MIME types
Make sure your multipart boundaries match up (and are unique)
Finicky problems with the number of line breaks (\n) after certain lines
Best of luck. I don't know if there is an open library that will do this sort of thing for you in C#. If you can find one then try use it, because dealing with the intricacies of the RFC should have a medical notice for increased blood pressure and hair loss.

Categories