【问题标题】:GMAIL API sending email with attachment in c#GMAIL API 在 C# 中发送带附件的电子邮件
【发布时间】:2014-12-11 10:27:47
【问题描述】:

我在使用 C# 中的 Gmail Api 发送带附件的电子邮件方面需要帮助。

我已经阅读了有关发送带有附件的电子邮件的 Google 网站,但示例是用 java 编写的。

【问题讨论】:

标签: gmail-api


【解决方案1】:

使用 Gmail API 发送附件没有什么特别之处。无论哪种方式,Gmail API message.send() 都会在 message.raw 字段(urlsafe base64 编码)中获取完整的 RFC822 电子邮件。主要技巧是用您的语言构建这样的 RFC822 电子邮件消息字符串。我想 C# 中有一些 MIME 消息库,而主要问题是找到这些库。我不做 C#,但 javax.internet.mail.MimeMessage 在 java 中运行良好,'email' 模块对 python 很好。

其他帖子似乎相关: How to send multi-part MIME messages in c#?

【讨论】:

    【解决方案2】:

    我在 VB.net 中有一个示例。 GMail API Emails Bouncing.

    Google 页面仅提供 Java 和 Python 示例。 Java 示例中使用的对象在 .Net 版本的 API 中不可用。无法翻译这些示例。

    幸运的是,在 C#/VB 中也很容易做到这一点。只需使用普通的旧 Net.Mail.MailMessage 创建包含附件的消息,然后使用 MimeKit (NuGet it) 将消息转换为字符串并将字符串(编码 Base64 后)传递给 Gmail API 的 message.send 的“Raw”字段.

    【讨论】:

      【解决方案3】:

      答案为时已晚,但发布以防万一有人需要它:)

      为此需要 MimeKit 库:可以从 NuGet 安装。

      代码:

      public void SendHTMLmessage()
      {
          //Create Message
          MailMessage mail = new MailMessage();
          mail.Subject = "Subject!";
          mail.Body = "This is <b><i>body</i></b> of message";
          mail.From = new MailAddress("fromemailaddress@gmail.com");
          mail.IsBodyHtml = true;
          string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
          mail.Attachments.Add(new Attachment(attImg));
          mail.To.Add(new MailAddress("toemailaddress.com.au"));
          MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
      
          Message message = new Message();
          message.Raw = Base64UrlEncode(mimeMessage.ToString());
          //Gmail API credentials
          UserCredential credential;
          using (var stream =
              new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
          {
              string credPath = System.Environment.GetFolderPath(
                  System.Environment.SpecialFolder.Personal);
              credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
      
              credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  GoogleClientSecrets.Load(stream).Secrets,
                  Scope,
                  "user",
                  CancellationToken.None,
                  new FileDataStore(credPath, true)).Result;
              Console.WriteLine("Credential file saved to: " + credPath);
          }
      
          // Create Gmail API service.
          var service = new GmailService(new BaseClientService.Initializer()
          {
              HttpClientInitializer = credential,
              ApplicationName = ApplicationName,
          });
          //Send Email
          var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
      }
      

      范围可以是:

      GmailSend 或 GmailModify

      static string[] Scope = { GmailService.Scope.GmailSend };
      static string[] Scope = { GmailService.Scope.GmailModify };
      

      Base64UrlEncode 函数:

      private string Base64UrlEncode(string input)
      {
          var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
          return Convert.ToBase64String(inputBytes)
            .Replace('+', '-')
            .Replace('/', '_')
            .Replace("=", "");
      }
      

      【讨论】:

      猜你喜欢
      • 2016-09-22
      • 2017-07-24
      • 2016-09-28
      • 2015-04-16
      • 2015-10-25
      • 2019-05-22
      • 2016-07-19
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多