Creating a Message for Gmail API in C#

前端 未结 3 1613
离开以前
离开以前 2020-12-16 16:31

I\'m looking at using the Gmail API in an application I\'m working on. However, I\'m not sure how to change their Java or Python examples over to C#. How exactly does the ex

3条回答
  •  醉梦人生
    2020-12-16 17:13

    Here is what I was able to get working, using 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("=", "");
    }
    

    Note: If you are getting an email bounce issue, it is likely due to not setting the ReplyToList field. See: GMail API Emails Bouncing

提交回复
热议问题