Add list-unsubscribe header with Amazon SES - c#

I'm searching for an working C# example to add list-unsubscribe header with Amazon SES.
After reading that Amazon-SES now supports adding Headers I was searching for an C# example but was unable to find one.

I couldn't find nice API like they have for Java. For C#, I found two alternative.
The easiest option is probably to switch to the SMTP interface and .Net's native SMTP classes (or a third-party library): Send an Email Using SMTP with C#
The example code is using the MailMessage class from System.Net.Mail:
// Create and build a new MailMessage object
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress(FROM,FROMNAME);
message.To.Add(new MailAddress(TO));
message.Subject = SUBJECT;
message.Body = BODY;
// Comment or delete the next line if you are not using a configuration set
message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);
Another (less attractive) option is to use SendRawEmailRequest. With this API, you have to encode the message along with its headers, attachments, and other data, in a MemoryStream.
Example code, from the AWS SDK .Net documentation - SES - RawMessage:
var sesClient = new AmazonSimpleEmailServiceClient();
var stream = new MemoryStream(
Encoding.UTF8.GetBytes("From: johndoe#example.com\n" +
"To: janedoe#example.com\n" +
"Subject: You're invited to the meeting\n" +
"Content-Type: text/plain\n\n" +
"Please join us Monday at 7:00 PM.")
);
var raw = new RawMessage
{
Data = stream
};
var to = new List<string>() { "janedoe#example.com" };
var from = "johndoe#example.com";
var request = new SendRawEmailRequest
{
Destinations = to,
RawMessage = raw,
Source = from
};
sesClient.SendRawEmail(request);

Related

Not getting any clue to integrate Gmail API using .NET framework in vs2017. I wanted to send the input data of the Web form to a user's email .

The official Gmail API documentation is horrendous. Not getting any clue to integrate Gmail API using .NET framework in vs2017. I wanted to send the input data of the Web form to a user's email.
It would be a three step process -
Define an HTML template which which describes how your mail should be presented.
Write a small c# code to replace all place holders like your form fields , user name, etc.
private string createEmailBody(string userName, string title, string message)
{
string body = string.Empty;
//using streamreader for reading my htmltemplate
using(StreamReader reader = new StreamReader(Server.MapPath("~/HtmlTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName); //replacing the required things
body = body.Replace("{Title}", title);
body = body.Replace("{message}", message);
//// Instead of message add you own parameters.
return body;
}
When form is submitted, call step 2 code first. Then use it's output to set mail body.
Code would be something like -
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
/// This mail from can just be a display only mail I'd
string emailFrom = "no-reply#gmail.com";
string subject = "your subject";
string body = createEmailBody();
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
/// Add more to IDs if you want to send it to multiple people.
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// This is required to keep formatting of your html contemts
/// Add attachments if you want, this is optional
mail.Attachments.Add(new Attachment(yourfilepath));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(your-smtp-account-email, your-smtp-account-password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Refer this link for working example
https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/
EDIT: For using GMail API
Using GMAIL APIs you will need two nuget packages:
1. Install-Package Google.Apis.Gmail.v1
2. Install-Package AE.Net.Mail
Code is very similar to what we have for normal SMTP mail send. It is explained at: http://jason.pettys.name/2014/10/27/sending-email-with-the-gmail-api-in-net-c/

Can I send files via email using MailKit?

As the title, is MailKit supported to send file?
If yes, how can I do it?
Yes. This is explained in the documentation as well as the FAQ.
From the FAQ:
How do I create a message with attachments?
To construct a message with attachments, the first thing you'll need to do is create a multipart/mixed container which you'll then want to add the message body to first. Once you've added the body, you can then add MIME parts to it that contain the content of the files you'd like to attach, being sure to set the Content-Disposition header value to the attachment. You'll probably also want to set the filename parameter on the Content-Disposition header as well as the name parameter on the Content-Type header. The most convenient way to do this is to simply use the MimePart.FileName property which
will set both parameters for you as well as setting the Content-Disposition header value to attachment if it has not already been set to something else.
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
Content = new MimeContent (File.OpenRead (path)),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;
A simpler way to construct messages with attachments is to take advantage of the
BodyBuilder class.
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder ();
// Set the plain-text version of the message text
builder.TextBody = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
";
// We may also want to attach a calendar event for Monica's party...
builder.Attachments.Add (#"C:\Users\Joey\Documents\party.ics");
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody ();
For more information, see Creating Messages.
#jstedfast brought pretty cool solution, here are a few more examples of simple ways to just send a file as an attachment (pdf document in this case, but can be applied to any file type).
var message = new MimeMessage();
// add from, to, subject and other needed properties to your message
var builder = new BodyBuilder();
builder.HtmlBody = htmlContent;
builder.TextBody = textContent;
// you can either create MimeEntity object(s)
// this might get handy in case you want to pass multiple attachments from somewhere else
byte[] myFileAsByteArray = LoadMyFileAsByteArray();
var attachments = new List<MimeEntity>
{
// from file
MimeEntity.Load("myFile.pdf"),
// file from stream
MimeEntity.Load(new MemoryStream(myFileAsByteArray)),
// from stream with a content type defined
MimeEntity.Load(new ContentType("application", "pdf"), new MemoryStream(myFileAsByteArray))
}
// or add file directly - there are a few more overloads to this
builder.Attachments.Add("myFile.pdf");
builder.Attachments.Add("myFile.pdf", myFileAsByteArray);
builder.Attachments.Add("myFile.pdf", myFileAsByteArray , new ContentType("application", "pdf"));
// append previously created attachments
foreach (var attachment in attachments)
{
builder.Attachments.Add(attachment);
}
message.Body = builder.ToMessageBody();
Hope it helps.
You can also send multiple files using this approach directly.
**Note: files used here is IEnumerable files **
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailService.FromFullName, emailService.FromEmail));
message.To.AddRange(emailsToSend.Select(x => new MailboxAddress(x)));
message.Subject = subject;
var builder = new BodyBuilder();
builder.HtmlBody = body;
foreach (var attachment in files)
{
if (attachment.Length > 0)
{
string fileName = Path.GetFileName(attachment.FileName);
builder.Attachments.Add(fileName, attachment.OpenReadStream());
}
}
message.Body = builder.ToMessageBody();
}

Exchange WebService sends only plain Text through c#

I have a program that sends eMail through the Exchange Webservice:
//EXCHANGE API
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
//BODY
string mBody = "<strong>TEXT</strong> Test";
//SETUP
ExchangeService service = new ExchangeService();
service.Url = new Uri("https://"+uriVar);
service.Credentials = new WebCredentials(userNameVar, passwordVar);
EmailMessage message = new EmailMessage(service);
message.Subject = mSubject;
message.Body = new MessageBody(BodyType.HTML,mBody);
message.ToRecipients.Add(recipient);
message.Save();
//Adding Image(s)
string fileFacebook = "facebook.png";
message.Attachments.AddFileAttachment("facebook.png", fileFacebook);
message.Attachments[0].IsInline = true;
message.Attachments[0].ContentId = "imgFacebook";
//Send
message.Send();
(the image is added in the original body, not in this example)
However, the eMail goes through as plain text, I cannot find out why. I am pretty sure it worked some time ago, is it possible that something has been changed on the Server? If so, what could it be?

Mail body: & becomes (R)

We have a site from where we send a auto generated mail to our customer when a new customer register. our mail got a activation link which look like
http://www.bba-reman.com/catalogue/ConfirmRegistration.aspx?email=meyer#reman.de&id=907a5253-106c-4fb3-9882-83e634e651b2
but when our german customer reveive the mail then he got the below activation link where you notice & character change to ®
http://www.bba-reman.com/catalogue/ConfirmRegistration.aspx?email=meyer#reman.de®id=907a5253-106c-4fb3-9882-83e634e651b2
Can anyone tell me why & character getting change to ®?
How to resolve this kind of problem?
try using CreateAlternateViewFromString property, here is the example code
MailMessage emailmsg = new MailMessage("from#address.co.za", "to#address.co.za")
emailmsg.Subject = "Subject";
emailmsg.IsBodyHtml = false;
emailmsg.ReplyToList.Add("from#address.co.za");
emailmsg.BodyEncoding = System.Text.Encoding.UTF8;
emailmsg.HeadersEncoding = System.Text.Encoding.UTF8;
emailmsg.SubjectEncoding = System.Text.Encoding.UTF8;
emailmsg.Body = null;
var plainView = AlternateView.CreateAlternateViewFromString(EmailBody, emailmsg.BodyEncoding, "text/plain");
plainView.TransferEncoding = TransferEncoding.SevenBit;
emailmsg.AlternateViews.Add(plainView);
SmtpClient sSmtp = new SmtpClient();
sSmtp.Send(emailmsg);

format email body - .net 4.0

I'm using the following to send email from a site done in .net 4, c#.
MailMessage nMail = new MailMessage();
nMail.To.Add("new.address#test.com");
nMail.From = new MailAddress("me#me.com");
Mail.Subject = (" ");
nMail.Body = (" ");
SmtpClient sc = new SmtpClient("our server");
sc.Credentials = new System.Net.NetworkCredential("login", "pwd");
sc.Send(nMail);
Works fine, only thing I don't know how to do is format the body of the message to have multiple lines and include fields from the page itself.
Any pointers?
This is one way to make a message body with multiple lines.
var bodyBuilder = new StringBuilder();
bodyBuilder.AppendLine("First line.");
bodyBuilder.AppendLine("Second line.");
nMail.Body = bodyBuilder.ToString();
It should be obvious how to pull in values from your form now, too (i.e., the full power of string formatting is at your disposal now).
Follow this article. this will guide you through the way on how to format the mail body.
You can send message as HTML. Use IsBodyHtml property
MailMessage nMail = new MailMessage();
nMail.To.Add("new.address#test.com");
nMail.From = new MailAddress("me#me.com");
Mail.Subject = (" ");
nMail.Body = ("Line<br/>New line");
nMail.IsBodyHtml = true;
SmtpClient sc = new SmtpClient("our server");
sc.Credentials = new System.Net.NetworkCredential("login", "pwd");
sc.Send(nMail);
carefully look at this example, it should help how to pull in values from your form too (not the best method used though).

Categories

Resources