本文介绍了使用 Amazon-SES 发送附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可用的 C# 示例来使用 Amazon-SES 发送附件.

I'm searching for an working C# example to send attachments with Amazon-SES.

阅读后 亚马逊-SES 现在支持发送附件,我正在搜索 C# 示例,但找不到.

After reading that Amazon-SES now supports sending attachments I was searching for an C# example but was unable to find one.

推荐答案

我认为使用 AWS SDK for .NETMimeKit 非常简单和干净解决方案.您可以通过 SES API(而不是 SMTP)发送带有附件的电子邮件.

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).

您可以将 MimeMessage 直接写入 MemoryStream,然后与 SES SendRawEmail 一起使用:

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", "[email protected]"));
    message.To.Add(new MailboxAddress(string.Empty, "[email protected]"));
    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);
        }
    }
}

这篇关于使用 Amazon-SES 发送附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 11:46