GMail API Emails Bouncing

女生的网名这么多〃 提交于 2019-11-28 13:31:28

This is crazy. This was the issue.

This line

msg.ReplyTo = New MailAddress(FromEmail, SenderName)

for whatever reasons (I guess when FromEmail and ReplyTo are same emails) leaves the RFC2822 Reply-To parameter blank. The parameter remains blank even when msg.ReplyTo is commented. Needless to say GMail API seems to have issues with Reply-To being left blank. Most definitely a programming bug.

So I had to do this hack in the final RFC2882 message.

inputTxt = Replace(inputTxt, "Reply-To:", "Reply-To: " & FromEmail)

It works now.

********* as pointed out in the comment below, you can use MailMessage.ReplyToList.Add() instead to solve this issue. So the issue here is that ReplyTo address is required in Gmail API (even though one might assume that ReplyTo should default to From email). **********

Just in case somebody stumbles across this and wants a C# answer, here is what I was able to get working using the previous answer as a guide, with MimeKit.

public void SendEmail(MyInternalSystemEmailMessage email)
{
    var mailMessage = new System.Net.Mail.MailMessage();
    mailMessage.From = new System.Net.Mail.MailAddress(email.FromAddress);
    mailMessage.To.Add(email.ToRecipients);
    mailMessage.ReplyToList.Add(email.FromAddress);
    mailMessage.Subject = email.Subject;
    mailMessage.Body = email.Body;
    mailMessage.IsBodyHtml = email.IsHtml;

    foreach (System.Net.Mail.Attachment attachment in email.Attachments)
    {
        mailMessage.Attachments.Add(attachment);
    }

    var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

    var gmailMessage = new Google.Apis.Gmail.v1.Data.Message {
        Raw = Encode(mimeMessage.ToString())
    };

    Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, ServiceEmail);

    request.Execute();
}

public static string Encode(string text)
{
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);

    return System.Convert.ToBase64String(bytes)
        .Replace('+', '-')
        .Replace('/', '_')
        .Replace("=", "");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!