回复c#中的电子邮件

时间:2017-11-10 07:03:12

标签: c# asp.net gmail-api reply

如何使用c# asp.net中的 gmail API 回复电子邮件,以便制作所有邮件的路径。获得pythonphpjavascript在线但不包含c#的解决方案。我可以获取消息详细信息,但不知道如何回复。

获取消息的代码:

public void getmessage()
{
    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);
    }
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
    var re = service.Users.Messages.List("me");
    re.LabelIds = "INBOX";
    re.Q = "from:emailaddress AND subject:subject";

    var res = re.Execute();

    if (res != null && res.Messages != null)
    {
        DataTable dt = new DataTable("msgs");
        dt.Columns.Add("Date");
        dt.Columns.Add("From");
        dt.Columns.Add("Subject");
        dt.Columns.Add("Body");
        foreach (var email in res.Messages)
        {
            var emailInfoReq = service.Users.Messages.Get("me", email.Id);
            var emailInfoResponse = emailInfoReq.Execute();
            if (emailInfoResponse != null)
            {
                String from = "";
                String date = "";
                String subject = "";
                String body = "";
                //loop through the headers and get the fields we need...
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    if (mParts.Name == "Date")
                    {
                        date = mParts.Value;
                    }
                    else if (mParts.Name == "From")
                    {
                        from = mParts.Value;
                    }
                    else if (mParts.Name == "Subject")
                    {
                        subject = mParts.Value;
                    }
                    //else if (mParts.Name == "Message-ID")
                    //{
                    //    var abc = mParts.Value;
                    //}
                    if (date != "" && from != "")
                    {
                        if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null)
                            body = DecodeBase64String(emailInfoResponse.Payload.Body.Data);
                        else
                            body = GetNestedBodyParts(emailInfoResponse.Payload.Parts, "");

                    }
                }
                DataRow row = dt.NewRow();
                row[0] = date;
                row[1] = from;
                row[2] = subject;
                row[3] = body;
                dt.Rows.Add(row);
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

获取消息ID ,但第一封电子邮件没有参考 In-Rely-To 。可以使用 MimeKit 发送简单的电子邮件,但不知道回复。

任何帮助将不胜感激。提前谢谢!!

1 个答案:

答案 0 :(得分:0)

最后能够在回答this.的帮助下做到这一点。如果有人想要,只需发布​​答案。

首先使用要回复的gmail API以RAW格式获取特定消息并将其转换为MimeMessage,以将其传递给Reply方法以创建回复消息并最终发送:

var emailInfoReq = service.Users.Messages.Get("me", email.Id);
emailInfoReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw; 
var emailInfoResponse = emailInfoReq.Execute();
if (emailInfoResponse != null)
{
  var message = emailInfoResponse.Raw;
  byte[] Msg = Base64UrlDecode(message);
  MemoryStream mm = new MemoryStream(Msg);
  MimeKit.MimeMessage Message1  = MimeKit.MimeMessage.Load(mm);
  MimeKit.MimeMessage Message = Reply(Message1, false);
  Message message1 = new Message();
  message1.Raw = Base64UrlEncode(Message.ToString());
  var result = service.Users.Messages.Send(message1, "me").Execute();
}

回复方法:

public static MimeKit.MimeMessage Reply(MimeKit.MimeMessage message, bool replyToAll)
{
 var reply = new MimeKit.MimeMessage();
 if (message.ReplyTo.Count > 0)
  {
   reply.To.AddRange(message.ReplyTo);
  }
 else if (message.From.Count > 0)
  {
  reply.To.AddRange(message.From);
  }
  else if (message.Sender != null)
  {
  reply.To.Add(message.Sender);
  }
  if (replyToAll)
  {
  reply.To.AddRange(message.To);
  reply.Cc.AddRange(message.Cc);
  }
  if (!message.Subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase))
    reply.Subject = "Re:" + message.Subject;
  else
    reply.Subject = message.Subject;
  if (!string.IsNullOrEmpty(message.MessageId))
  {
    reply.InReplyTo = message.MessageId;
    foreach (var id in message.References)
      reply.References.Add(id);
      reply.References.Add(message.MessageId);
  }
  using (var quoted = new StringWriter())
  {
    var sender = message.Sender ?? message.From.Mailboxes.FirstOrDefault();
    quoted.WriteLine("On {0}, {1} wrote:", message.Date.ToString("f"), !string.IsNullOrEmpty(sender.Name) ? sender.Name : sender.Address);
    using (var reader = new StringReader(message.TextBody))
    {
      string line;
      while ((line = reader.ReadLine()) != null)
      {
        quoted.Write("> ");
        quoted.WriteLine(line);
      }
    }
    reply.Body = new MimeKit.TextPart("plain")
    {
      Text = quoted.ToString()
    };
  }
  return reply;
}