AWS SES SendRawEmailAsync 不欢迎 BCC [英] AWS SES SendRawEmailAsync not entertaining BCC

查看:26
本文介绍了AWS SES SendRawEmailAsync 不欢迎 BCC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AWS SES Api 发送电子邮件,将邮件消息转换为流,但我无法发送密件抄送.

I am sending the email using AWS SES Api, by converting the mail message into the stream, but i am not able to send the BCC.

private async Task<bool> SendMessageUsingAWSProfileAsync(EmailMessage message, CancellationToken token)
    {

        MailMessage mailMessage = GetMailMessage(message);

        if (mailMessage == null)
        {
            _logger.DebugFormat("Unable to create MailMessage from message: {0}.", message);
            return false;
        }

        SendRawEmailResponse response;
        var credentials = new BasicAWSCredentials(_settings.GetString("AWS.Key"), _settings.GetString("AWS.Secret"));
        using (var amazonClient = new AmazonSimpleEmailServiceClient(credentials, _awsRegion))
        {
            using (MemoryStream stream = ConvertMailMessageToMemoryStream(mailMessage))
            {
                // Send Email using AWS API
                var rawMessage = new RawMessage(stream);

                List<String> destinations = new List<string>();


                var sendRequest = new SendRawEmailRequest(rawMessage)
                {
                    Source = mailMessage.From.Address,
                };

                response = await amazonClient.SendRawEmailAsync(sendRequest, token).ConfigureAwait(false);
            }
        }

        message.MessageId = response.MessageId;
        message.FromServiceId = _settings.GetString("AWS.Key");
        message.CommunicationDirectionEnum = CommunicationDirectionEnum.Out;
        await LogMessageAsync(message, token).ConfigureAwait(false);

        await AuditMessageAsync(message, token).ConfigureAwait(false);

        return true;
    }


 private MailMessage GetMailMessage(EmailMessage message)
    {
        if (message == null) throw new ArgumentNullException(nameof(message));

        if (string.IsNullOrEmpty(message?.Body))
        {
            _logger.DebugFormat("Empty email body.");
            return null;
        }

        if (string.IsNullOrEmpty(message.ToEmailID))
        {
            _logger.DebugFormat("To EmailID is empty.");
            return null;
        }

        List<string> mailAddresses = GetToEmailList(message.ToEmailID);
        List<string> bccMailAddresses = GetToEmailList(message.BccEmailId);
        if (mailAddresses == null || mailAddresses.Count == 0)
        {
            _logger.DebugFormat("No valid To EmailID.");
            return null;
        }
        var result = new MailMessage();

        foreach (var toAddress in mailAddresses)
        {
            result.To.Add(new MailAddress(toAddress));
        }

        foreach (var bccAddress in bccMailAddresses)
        {
            result.Bcc.Add(new MailAddress(bccAddress));
        }



        return result;
    }

public static MemoryStream ConvertMailMessageToMemoryStream(MailMessage message)
    {
        Assembly assembly = typeof(SmtpClient).Assembly;
        Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
        var stream = new MemoryStream()
            ConstructorInfo mailWriterConstructor =
                mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null,
                    new[] { typeof(Stream) }, null);

        object mailWriter = mailWriterConstructor.Invoke(new object[] { stream });

        MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send",
            BindingFlags.Instance | BindingFlags.NonPublic);

        sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null,
            new[] { mailWriter, true, true }, null);

        MethodInfo closeMethod = mailWriter.GetType()
            .GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);

        closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { },
            null);
        return stream;
    }

BCC 已经在 mailMessage 对象中,所以当它把它转换成 raw 时,它也应该将 BCC 包含在标题中.我试过包括/排除目的地,它给出了相同的结果.

The BCC is already into the mailMessage object, so when its converting it to raw, it should be include BCC into the headers too. I have tried including/ excluding destinations, it gives the same result.

非常感谢任何帮助.

推荐答案

所以最终通过对代码进行以下 2 处更改使其工作

So finally made it work by doing following 2 changes to code

1 - 在 SendMessageUsingAWSProfileAsync(, 删除目的地,因为它不接受 BCC

1 - In SendMessageUsingAWSProfileAsync(, Remove the desintation as it does not entertain BCC

                var sendRequest = new SendRawEmailRequest(rawMessage)
                {
                    Source = mailMessage.From.Address, // Destionation is removed from here intenationally as it stop doing BCC

}

2 - 在 ConvertMailMessageToMemoryStream 中,在从邮件消息创建流时包含 BCC 标头

2 - In ConvertMailMessageToMemoryStream, Include BCC headers while creating the stream from mail message

// BCC is not included by default, so need to include it.
        if (message.Bcc.Count > 0)
        {
            MethodInfo writeHeadersMethod = mailWriter.GetType().GetMethod("WriteHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
            System.Collections.Specialized.NameValueCollection bccHeaders = new System.Collections.Specialized.NameValueCollection();
            bccHeaders.Add("BCC", string.Join(",", message.Bcc.Select(b => b.Address)));
            writeHeadersMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { bccHeaders, false }, null);
        }

这篇关于AWS SES SendRawEmailAsync 不欢迎 BCC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆