AWS SES 无法附加文件

AWS SES not able to get a file attached

提问人:Kaptindan 提问时间:10/31/2023 更新时间:11/1/2023 访问量:23

问:

使用 AWS SES 服务,我似乎无法添加文件附件

亚马逊 SES 需要 AWS 账户和设置 将 [email protected] 替换为您的“发件人”地址。 此地址必须通过 Amazon SES 进行验证。 字符串 FROM = “*****@gmail.com”; 字符串 FROMNAME = “丹尼”;

                // Replace [email protected] with a "To" address. If your account
                // is still in the sandbox, this address must be verified.
                String TO = s;

                // Replace smtp_username with your Amazon SES SMTP user name.
                String SMTP_USERNAME = "****";

                // Replace smtp_password with your Amazon SES SMTP password.
                String SMTP_PASSWORD = "*********";

                // (Optional) the name of a configuration set to use for this message.
                // If you comment out this line, you also need to remove or comment out
                // the "X-SES-CONFIGURATION-SET" header below.
                String CONFIGSET = "ConfigSet";

                // If you're using Amazon SES in a region other than US West (Oregon),
                // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP  
                // endpoint in the appropriate AWS Region.
                String HOST = "email-smtp.us-east-2.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.
                int PORT = 587;

                // The subject line of the email
                String SUBJECT =
                    "Amazon SES test (SMTP interface accessed using C#)";

                String attachment = "C:\\20231030.csv";

                // The body of the email
                String BODY =
                    "<h1>Amazon SES Test</h1>" +
                    "<p>This email was sent through the " +
                    "<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
                    "using the .NET System.Net.Mail library.</p>" +
                    "<p>Last Hours Total was " + txtLastHour.Text + "<p>" + "" +
                    "<p>Yesterdays Total was " + txtTotal.Text + " " + "" +
                    "<p>Total Bad Reads from Yesterday " + txtBadRead.Text + "<p> " + "" +
                    "<p>Total Jackpot from Yesterday " + txtJackpot.Text + "<p> " + "";
            
                // 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);

                                    
                using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
                {
                    client.UseDefaultCredentials = false;
                    // Pass SMTP credentials
                    client.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
                    
                    // Enable SSL encryption
                    client.EnableSsl = true;

                
                    // Try to send the message. Show status in console.
                    try
                    {
                        Console.WriteLine("Attempting to send email...");
                        client.Send(message);
                        Console.WriteLine("Email sent!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("The email was not sent.");
                        Console.WriteLine("Error message: " + ex.Message);
                    }

                }
C# 亚马逊 SES

评论

0赞 AztecCodes 11/1/2023
欢迎来到 Stack Overflow!谢谢你的提问。但是,您似乎不熟悉 Stack Overflow 到如何:问一个好问题的指南。请阅读它并使用“编辑”选项相应地调整您的问题。祝您编码愉快!

答:

0赞 rlhagerm 11/1/2023 #1

要添加用于使用 SES 发送的附件,您可以使用“原始邮件”操作。示例代码库中有一个更详细的示例,用于执行此操作,并具有 .NET 版本。您应该转到 GitHub 链接以查看完整代码,但这里是主要部分,它使用 MimeKit 在 C# 的原始消息中获取正确的格式。

 public async Task<string> SendReport(IList<WorkItem> workItems, string emailAddress)
{
    await using var attachmentStream = new MemoryStream();
    await using var streamWriter = new StreamWriter(attachmentStream);
    await using var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
    await GetCsvStreamFromWorkItems(workItems, attachmentStream, streamWriter, csvWriter);

    await using var messageStream = new MemoryStream();
    var plainTextBody = GetReportPlainTextBody(workItems);
    var htmlBody = GetReportHtmlBody(workItems);
    var attachmentName = $"activeWorkItems_{DateTime.Now:g}.csv";
    var subject = $"Item Tracker Report: Active Work Items {DateTime.Now:g}";

    await BuildRawMessageWithAttachment(emailAddress, plainTextBody, htmlBody, subject, attachmentName, attachmentStream, messageStream);

    var response = await _amazonSESService.SendEmailAsync(
        new SendEmailRequest
        {
            Destination = new Destination
            {
                ToAddresses = new List<string> { emailAddress }
            },
            Content = new EmailContent()
            {
                Raw = new RawMessage()
                {
                    Data = messageStream
                }
            },
        });

    return response.MessageId;
}

/// <summary>
/// Build a raw message memory stream with an attachment.
/// </summary>
public async Task BuildRawMessageWithAttachment(string emailAddress, string textBody, string htmlBody, string subject, string attachmentName,
    MemoryStream attachmentStream, MemoryStream messageStream)
{
    // The email with attachment can be created using MimeKit.
    var fromEmailAddress = _configuration["EmailSourceAddress"];

    var message = new MimeMessage();
    var builder = new BodyBuilder()
    {
        TextBody = textBody,
        HtmlBody = htmlBody
    };

    message.From.Add(new MailboxAddress(fromEmailAddress, fromEmailAddress));
    message.To.Add(new MailboxAddress(emailAddress, emailAddress));
    message.Subject = subject;

    await builder.Attachments.AddAsync(attachmentName, attachmentStream);

    message.Body = builder.ToMessageBody();
    await message.WriteToAsync(messageStream);
}