簡體   English   中英

將存儲在 S3 存儲桶中的 Amazon SES 電子郵件轉換為 MimeMessage 類型 (MimeKit)

[英]Cast Amazon SES emails, stored in S3 buckets, to MimeMessage type (MimeKit)

我需要閱讀收到的電子郵件,但有以下限制:

  1. Amazon SES規則將傳入的電子郵件存儲到 S3 存儲桶;
  2. 然后需要將這些電子郵件轉換為 MimeKit C# 庫的MimeMessage類型,以便與遺留代碼很好地配合使用。

事情是當我嘗試將電子郵件轉換為 MimeMessage 時,出現異常“文件名、目錄名或卷標語法不正確”。

如何才能轉換為 MimeMessage? 我應該用 Regex 解析電子郵件的內容嗎?

我知道我可以將 Amazon SES 與 Amazon WorkMail 集成以接收 Mime 格式的消息,這對我來說會更容易。 但如果可以的話,我會避免訂閱亞馬遜的另一項付費服務。

我在下面發布了我的代碼和消息錯誤,以更好地說明問題:

    public GetMailController(AmazonS3Client s3Client, IConfiguration configuration)
    {
        _s3Client = s3Client;
        _config = configuration;
    }

    [HttpGet(Name = "Get")]
    public IEnumerable<MimeMessage> Get()
    {
        string AwsS3Bucket = _config.GetValue<string>("AwsS3Bucket");
        List<MimeMessage> mails = new();
        List<string> bucketKeys = GetBucketIds();
        foreach (string k in bucketKeys)
        {
            GetObjectResponse response = _s3Client.GetObjectAsync(new GetObjectRequest() { BucketName = AwsS3Bucket, Key = k }).GetAwaiter().GetResult();
            using (Stream responseStream = response.ResponseStream)
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string content = reader.ReadToEnd();
                try
                {
                
                    var mail = MimeMessage.LoadAsync(content).GetAwaiter().GetResult(); // Exception: "The filename, directory name or volume label syntax is incorrect."
                    mails.Add(mail);
                }
                catch (Exception exc)
                {
                    return null;

                }
            }
        }
        return mails;
    }

結果錯誤信息

The filename, directory name or volume label syntax is incorrect. 

我嘗試使用 MimeKit 方法MimeMessage.Load()來解析 MIME 格式的電子郵件,但The filename, directory name or volume label syntax is incorrect.

MimeMessage.Load()方法期望接收文件名(文件路徑)或作為參數。

由於您向它提供了流的等效字符串,它認為您向它提供了一個文件名 - 因此filename 、 directory name 或 volume label syntax is incorrect錯誤。

直接使用從GetObjectResponse獲得的流,如下所示:

GetObjectResponse response = _s3Client.GetObjectAsync(new GetObjectRequest() { BucketName = AwsS3Bucket, Key = k }).GetAwaiter().GetResult();
using (Stream responseStream = response.ResponseStream)
{
    try
    {
        var mail = MimeMessage.Load(responseStream);
        mails.Add(mail);
    }
    catch (Exception exc)
    {
        return null;
    }
}

我還建議使用await而不是.GetAwaiter().GetResult()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM