Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-Converting Gmail MessageParts into Readable Text

I have looked all over the place and keep running into dead ends.

I am trying to use the Google APIs to download gmail into a C# plugin and then place it into a created Mail Object Class that the parent program can understand.

I have gotten to the point of being able to download the Messages and I can get everything except the actual E-Mail body, which is buried deeply in the payload's MessagePart structure.

What I am after is a way to convert the Payload's Parts into Richtext or HTML if possible, or pure text if not.

At the moment I don't need to have any image attachments come through, just the text in the body.

GmailService gs = new GmailService(new Google.Apis.Services.BaseClientService.Initializer() {   ApplicationName = Constant.clientId, HttpClientInitializer = credential });

UsersResource.MessagesResource messagesResource = gs.Users.Messages;
IList<Message> messages = messagesResource.List(userGmail.Value).Execute().Messages;
foreach (Message message in messages)
{
   String messageID = message.Id;
   ReceivedGmail check = ObjectSpace.RetrieveObjectByKeyProperty<ReceivedGmail>(messageID);

   if (check == null)
   {
       messagesResource.Get(userGmail.Value, messageID).Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;

       Message mail = messagesResource.Get(userGmail.Value, messageID).Execute();
       MessagePart mailbody = mail.Payload;

       ReceivedGmail gmail = new ReceivedGmail() { User = User.CurrentUser, Unread = true, mailID = messageID };

       //Get all the header information from the message (Date, Emails, etc.) and add to gmail object.

       //gmail.body = ?????;

       ObjectSpace.StoreObject<ReceivedGmail>(gmail);
    }
}

Any help on how to get the data I need to add into gmail.body would be greatly appreciated.

like image 237
Stephen Hammond Avatar asked Mar 19 '23 13:03

Stephen Hammond


1 Answers

Okay a lot more searching and chasing and more dead ends until finally...

Since I had the MIME string, I just needed to do a few replacements and then decode it using base64

So the solution...

public static String GetMimeString(MessagePart Parts)
    {
        String Body = "";

        if (Parts.Parts != null)
        {
            foreach (MessagePart part in Parts.Parts)
            {
                Body = String.Format("{0}\n{1}", Body, GetMimeString(part));
            }
        }
        else if (Parts.Body.Data != null && Parts.Body.AttachmentId == null && Parts.MimeType == "text/plain")
        {
            String codedBody = Parts.Body.Data.Replace("-", "+");
            codedBody = codedBody.Replace("_", "/");
            byte[] data = Convert.FromBase64String(codedBody);
            Body = Encoding.UTF8.GetString(data);
        }

        return Body;
like image 160
Stephen Hammond Avatar answered Apr 01 '23 13:04

Stephen Hammond