如何创建Gmail API邮件 [英] How to create a Gmail API Message

查看:264
本文介绍了如何创建Gmail API邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Google的Gmail API发送邮件。我已经成功通过身份验证,正在尝试使用GmailService发送邮件。

I'd like to send a Message using Google's Gmail API. I've authenticated successfully, and am trying to use GmailService to send a message.

我想使用此功能:

myService.Users.Messages.Send(myMessage, "me").Execute();

其中myService是 Google.Apis.Gmail.v1.GmailService 和myMessage是 Google.Apis.Gmail.v1.Data.Message

where myService is a Google.Apis.Gmail.v1.GmailService and myMessage is a Google.Apis.Gmail.v1.Data.Message.

myService 很好,我完成了OAuth跳舞。我可以从收件箱中获取消息以及所有其他信息。但是我不知道如何构造 myMessage 。我有一个标准的.NET MailMessage ,具有人类可读的主题,正文,收件人,发件人等。

myService is fine, I've done the OAuth dance. I can get messages from my Inbox and all that. But I don't know how to construct myMessage. I have a standard .NET MailMessage, with human-readable Subject, Body, To, From etc.

但是Google Message 类接受有效负载 Raw 字段。将完整的 MailMessage 转换为字符串的最简单方法是什么,我可以将其设置为 Payload 原始属性?还是这根本不是我应该做的事情?

But the Google Message class takes fields Payload or Raw. What's the easiest way to convert a full MailMessage to a string which I can set to the Payload or Raw properties? Or is this not what I should be doing at all?

Message类的文档

推荐答案

我找到了解决方案。奇怪的是,.NET似乎并不原生/轻松地支持此功能。不过有一个不错的nuget包,叫做AE.Net.Mail,它可以将易于创建的消息对象写入流中。

I found a solution. Strangely, .NET doesn't seem to support this natively/easily. There's a nice nuget package though, called AE.Net.Mail, which can write an easy-to-create message object to a stream.

这是向我指出该示例的示例代码

由于站点似乎已关闭,因此复制并粘贴了代码,并且Google的缓存可能不会永远持续下去。

Copy-and-pasted code as site seems to be down, and Google's cache might not last forever:

using System.IO;
using System.Net.Mail;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

public class TestEmail {

  public void SendIt() {
    var msg = new AE.Net.Mail.MailMessage {
      Subject = "Your Subject",
      Body = "Hello, World, from Gmail API!",
      From = new MailAddress("[you]@gmail.com")
    };
    msg.To.Add(new MailAddress("yourbuddy@gmail.com"));
    msg.ReplyTo.Add(msg.From); // Bounces without this!!
    var msgStr = new StringWriter();
    msg.Save(msgStr);

    var gmail = new GmailService(Context.GoogleOAuthInitializer);
    var result = gmail.Users.Messages.Send(new Message {
      Raw = Base64UrlEncode(msgStr.ToString())
    }, "me").Execute();
    Console.WriteLine("Message ID {0} sent.", result.Id);
  }

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

这篇关于如何创建Gmail API邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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