1

How to reply back to an email message using gmail API in c# asp.net so that it make trails of all messages. Got solutions for python, php, javascript online but not for c#. I can get message details but don't know how to reply.

My code for getting message:

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();
    }
}

Getting message-ID as well but no References and In-Rely-To for first email. Can send simple email message using MimeKit but have no idea about reply.

Any help would be appreciated. Thank you in advance!!

Preet
  • 984
  • 2
  • 14
  • 34
  • You can try the examples in [SO post 1](https://stackoverflow.com/questions/45371120/send-a-mail-as-a-reply-using-smtpclient) and [SO post 2](https://stackoverflow.com/questions/449887/sending-e-mail-using-c-sharp). Both used the `SmtpClient` in which you can refer from [this documentation by MSDN](http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(VS.80).aspx). – MαπμQμαπkγVπ.0 Nov 12 '17 at 13:15
  • Thanks, will try this way if it works with gmai API as well – Preet Nov 13 '17 at 00:11

1 Answers1

0

Finally able to do it with the help of answer to this. Just posting answer if anybody wants.

First of all get specific message in RAW format using gmail API to which you wanna reply and convert it to MimeMessage to pass it to Reply method to create reply message and finally send it:

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();
}

The Reply Method:

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;
}
Preet
  • 984
  • 2
  • 14
  • 34