从gmail api

时间:2018-09-08 18:08:22

标签: c# html email office-interop gmail-api

我正在用C#开发一个软件,该软件将传入的电子邮件读取到gmail收件箱。 我正在使用Gmail API来检索电子邮件。

电子邮件的正文编码为base64,所以我正在使用以下方法对其进行解码:

byte[] data = FromBase64ForUrlString(p.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);

public static byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
        int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
        StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
        result.Append(String.Empty.PadRight(padChars, '='));
        result.Replace('-', '+');
        result.Replace('_', '/');
        return Convert.FromBase64String(result.ToString());
}

然后,我得到了电子邮件的html正文。 为了获取文本,我正在使用此方法(使用HtmlAgilityPack):

    public string ConvertHtml(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);

        StringWriter sw = new StringWriter();
        ConvertTo(doc.DocumentNode, sw);
        sw.Flush();
        return sw.ToString();
    }

现在,我面临着转换从Outlook发送的电子邮件的html正文的问题。看起来Outlook具有特殊的编码。

当我尝试转换这种主体时,我得到一个包含很多\ r \ n,\ n,\ r的字符串,这会在没有换行的地方导致换行。

直到现在,我通过使用Microsoft.Office.Interop.Outlook成功绕过了这一步。

我基本上要做的是创建一个Outlook电子邮件项目,将其htmlBody属性设置为我刚从gmail的api中获得的属性,然后从body属性中获得文本本身。

 Microsoft.Office.Interop.Outlook.Application objOutlook = newMicrosoft.Office.Interop.Outlook.Application();
 Microsoft.Office.Interop.Outlook.MailItem msgInterop =(Microsoft.Office.Interop.Outlook.MailItem)(objOutlook.CreateItem(                                                        
Microsoft.Office.Interop.Outlook.OlItemType.olMailItem));                                     
msgInterop.HTMLBody = decodedString;
if (msgInterop.Body != null)
   currEmailItem.Body = msgInterop.Body.ToString();

仅在安装了Outlook软件的计算机中可以执行此过程。

现在,我将软件移至操作系统为Windows Server的服务器上。

一开始,我虽然不愿意在服务器上安装Outlook,但是每次我的软件尝试访问Outlook时,它最多需要10分钟的访问时间,因此我想避免强制我执行以下操作的解决方案:使用Outlook。

也许您有不需要安装Outlook软件的解决方案?

0 个答案:

没有答案