Home > Mobile >  Set 'Sender Name' in Amazon SES in C#
Set 'Sender Name' in Amazon SES in C#

Time:01-15

I'm using Amazon SES in an ASP.net (Core) 6 App to send emails from my own domain - works well.

I want to change the 'From Name' so rather than seeing the email address users see 'Name' in their email client (eg 'John Smith' or 'Company Name').

This is the code that Amazon provide that sends the email:

var sender = "Name [email protected]";
var emailMessage = BuildEmailHeaders(sender, to, cc, bcc, subject);

var emailBody = BuildEmailBody(body, isHtmlBody);
emailMessage.Body = emailBody.ToMessageBody();
return SendEmailAsync(emailMessage);

With just email in the sender variable, it works fine.

Above I've tried adding a name first with a space as recommended by this article: https://kitefaster.com/2017/04/19/set-name-senderfromsource-amazon-ses/

but it returns a 500:

I've also tried this:

var sender = "Name<[email protected]>";

But it also returns 500

How can I change the sender name?

Thanks

CodePudding user response:

I am not sure how SendEmailAsync() is defined. I am using the code that is described here:

SmtpClient smtpClient = new() { ... };
MailMessage mailMessage = new ()
{
    From = new MailAddress("[email protected]", "Johnny"),
    Subject = "this is a test",
    Body = "some very important email"
};

smtpClient.Send(mailMessage);

and emails show as coming from Johnny

Needless to say, AWS documentation on ASP.NET is woefully outdated; but the example still works in .NET 6 and 7

CodePudding user response:

The answer was in another part of the example code provided by Amazon.

See "John Smith" below - it was just blank in the original example files.

    private static MimeMessage BuildEmailHeaders(string from, IEnumerable<string> to, IReadOnlyCollection<string> cc, IReadOnlyCollection<string> bcc, string subject)
    {
        var message = new MimeMessage();
        //message.From.Add(new MailboxAddress(string.Empty, from));
        message.From.Add(new MailboxAddress("John Smith", from));

        foreach (var recipient in to)
        {
            message.To.Add(new MailboxAddress(string.Empty, recipient));
        }
        if (cc != null && cc.Any())
        {
            foreach (var recipient in cc)
            {
                message.Cc.Add(new MailboxAddress(string.Empty, recipient));
            }
        }
        if (bcc != null && bcc.Any())
        {
            foreach (var recipient in bcc)
            {
                message.Bcc.Add(new MailboxAddress(string.Empty, recipient));
            }
        }
        message.Subject = subject;
        return message;
    }
  • Related