在生成的电子邮件中添加默认的outlook签名

本文关键字:默认 outlook 签名 添加 电子邮件 | 更新日期: 2023-09-27 17:59:53

我正在使用Microsoft.Office.Interop.Outlook.Application生成电子邮件并在用户发送之前将其显示在屏幕上。该应用程序是.NET Framework 3.5 SP1中用C#编码的winform应用程序,它是Microsoft Outlook 2003。我正在使用以下代码:

public static void GenerateEmail(string emailTo, string ccTo, string subject, string body)
    {
        var objOutlook = new Application();
        var mailItem = (MailItem)(objOutlook.CreateItem(OlItemType.olMailItem));        
        mailItem.To = emailTo;          
        mailItem.CC = ccTo;
        mailItem.Subject = subject;
        mailItem.HTMLBody = body;
        mailItem.Display(mailItem);
    }

我的问题是:

如何在生成的电子邮件的body中插入/添加正在使用该应用程序的用户的默认签名感谢您的帮助。

在生成的电子邮件中添加默认的outlook签名

有一种非常简单快捷的方法尚未提及。见以下修改:

public static void GenerateEmail(string emailTo, string ccTo, string subject, string body)
{
    var objOutlook = new Application();
    var mailItem = (MailItem)(objOutlook.CreateItem(OlItemType.olMailItem));        
    mailItem.To = emailTo;          
    mailItem.CC = ccTo;
    mailItem.Subject = subject;
    mailItem.Display(mailItem);
    mailItem.HTMLBody = body + mailItem.HTMLBody;
}

通过在显示邮件项目后编辑HTMLBody,Outlook可以完成添加默认签名的工作,然后基本上进行复制、编辑和附加。

查看下面的链接。它解释了在文件系统中可以在哪里找到签名,以及如何正确读取签名。

http://social.msdn.microsoft.com/Forums/en/vsto/thread/86ce09e2-9526-4b53-b5bb-968c2b8ba6d6

该线程只提到WindowsXP和WindowsVista的签名位置。我已经确认Outlooks在Windows7上的签名和Vista住在同一个地方。我还确认Outlook 2003、2007和2010的签名位置相同。

如果您选择走这条路,这里有一个代码示例。取自本网站。

private string ReadSignature()
{
    string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "''Microsoft''Signatures";
    string signature = string.Empty;
    DirectoryInfo diInfo = new DirectoryInfo(appDataDir);
    if(diInfo.Exists)
    {
        FileInfo[] fiSignature = diInfo.GetFiles("*.htm");
        if (fiSignature.Length > 0)
        {
            StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);
            signature = sr.ReadToEnd();
            if (!string.IsNullOrEmpty(signature))
            {
                string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);
                signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
            }
        }
    }
        return signature;
}

编辑:请参阅此处查找Outlook 2013的默认签名的名称或@japel在该线程中的2010答案。

我也遇到过完全相同的问题,但只能用Interop解决,从而获得默认签名。

诀窍是调用GetInspector,它将神奇地将HTMLBody属性设置为签名。仅仅读取GetInspector属性就足够了。我用Windows7/Outlook2007测试了这个。

感谢这篇博客文章的解决方案。

我发现了一种非常简单的方法来附加默认的outlook签名(包括图像)。诀窍是在调用GetInspector后检索正文消息,并将消息连接到该消息。

Imports Microsoft.Office.Interop
Dim fdMail As Outlook.MAPIFolder
Dim oMsg As Outlook._MailItem
oMsg = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
Dim olAccounts As Outlook.Accounts
oMsg.SendUsingAccount = olAccounts.Item(1)
oMsg.Subject = "XXX"
oMsg.To = "xxx@xxx.com"
Dim myInspector As Outlook.Inspector = oMsg.GetInspector
Dim text As String
text = "mail text" & oMsg.HTMLBody
oMsg.HTMLBody = text
oMsg.Send()

编辑日期:2021年3月5日请注意,当使用Office 365内部版本13530.20440或更高版本时,此方法似乎会失败。你会得到一个";对不起,出了问题。你可能想再试一次"消息仍在等待修复。如果在oMsg.Send()而不是getInspector方法之前调用oMsg.Display(),它会起作用,但用户会看到outlook窗口的闪烁。

我主要通过"偷偷摸摸"来解决这个问题。如果您在Outlook中通过Ctrl+N制作新电子邮件时,它插入默认签名,我将该空白电子邮件(带签名)存储在一个临时字符串中,然后将该字符串附加到另一个包含内容的字符串中。

这里有一些代码来演示它:

string s = "";
Outlook.Application olApp = new Outlook.Application();
Outlook.MailItem mail = olApp.CreateItem(Outlook.OlItemType.olMailItem);
mail.To = "Hi@World.com";
mail.Subject = "Example email";
s = mainContentAsHTMLString + mail.HTMLBody;
mail.Display();
mail.HTMLBody = s;

由于某些原因,库会根据安装的语言而有所不同。签名也可以保存一个标志图像,我不知道为什么,但它是在2个不同大小的文件中制作的。

private string ReadSignature()
    {
        string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "''Microsoft''Signatures";
        string signature = string.Empty;
        DirectoryInfo diInfo = new DirectoryInfo(appDataDir);
        if (diInfo.Exists)
        {
            FileInfo[] fiSignature = diInfo.GetFiles("*.htm");
            if (fiSignature.Length > 0)
            {
                StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);
                signature = sr.ReadToEnd();
                if (!string.IsNullOrEmpty(signature))
                {
                    string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);
                    signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
                }
            }
        }
        else
        {
            appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "''Microsoft''Signaturer";
            signature = string.Empty;
            diInfo = new DirectoryInfo(appDataDir);
            if (diInfo.Exists)
            {
                FileInfo[] fiSignature = diInfo.GetFiles("*.htm");
                if (fiSignature.Length > 0)
                {
                    StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);
                    signature = sr.ReadToEnd();
                    if (!string.IsNullOrEmpty(signature))
                    {
                        string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);
                        signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
                    }
                }
            }
        }
        if (signature.Contains("img"))
        {
            int position = signature.LastIndexOf("img");
            int position1 = signature.IndexOf("src", position);
            position1 = position1 + 5;
            position = signature.IndexOf("'"", position1);
            billede1 = appDataDir.ToString() + "''" + signature.Substring(position1, position - position1);
            position = billede1.IndexOf("/");
            billede1 = billede1.Remove(position, 1);
            billede1 = billede1.Insert(position, "''");
            billede1 = System.Web.HttpUtility.UrlDecode(billede1);
            position = signature.LastIndexOf("imagedata");
            position1 = signature.IndexOf("src", position);
            position1 = position1 + 5;
            position = signature.IndexOf("'"", position1);
            billede2 = appDataDir.ToString() + "''" + signature.Substring(position1, position - position1);
            position = billede2.IndexOf("/");
            billede2 = billede2.Remove(position, 1);
            billede2 = billede2.Insert(position, "''");
            billede2 = System.Web.HttpUtility.UrlDecode(billede2);
        }
        return signature;
    }

获取并插入签名:全局变量:

    string billede1 = string.Empty;    // holding image1
    string billede2 = string.Empty;    // holding image2
                        string signature = ReadSignature();
                        if (signature.Contains("img"))
                        {
                            int position = signature.LastIndexOf("img");
                            int position1 = signature.IndexOf("src", position);
                            position1 = position1 + 5;
                            position = signature.IndexOf("'"", position1);
                            //CONTENT-ID
                            const string SchemaPR_ATTACH_CONTENT_ID = @"http://schemas.microsoft.com/mapi/proptag/0x3712001E";
                            string contentID = Guid.NewGuid().ToString();
                            //Attach image
                            mailItem.Attachments.Add(@billede1, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailItem.Body.Length, Type.Missing);
                            mailItem.Attachments[mailItem.Attachments.Count].PropertyAccessor.SetProperty(SchemaPR_ATTACH_CONTENT_ID, contentID);
                            //Create and add banner
                            string banner = string.Format(@"cid:{0}", contentID);
                            signature = signature.Remove(position1, position - position1);
                            signature = signature.Insert(position1, banner);
                            position = signature.LastIndexOf("imagedata");
                            position1 = signature.IndexOf("src", position);
                            position1 = position1 + 5;
                            position = signature.IndexOf("'"", position1);
                            //CONTENT-ID
                           // const string SchemaPR_ATTACH_CONTENT_ID = @"http://schemas.microsoft.com/mapi/proptag/0x3712001E";
                            contentID = Guid.NewGuid().ToString();
                            //Attach image
                            mailItem.Attachments.Add(@billede2, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailItem.Body.Length, Type.Missing);
                            mailItem.Attachments[mailItem.Attachments.Count].PropertyAccessor.SetProperty(SchemaPR_ATTACH_CONTENT_ID, contentID);
                            //Create and add banner
                            banner = string.Format(@"cid:{0}", contentID);
                            signature = signature.Remove(position1, position - position1);
                            signature = signature.Insert(position1, banner);
                        }
                        mailItem.HTMLBody = mailItem.Body + signature;

串串可以做得更聪明,但这很管用,给了我灵感祝你好运。

对于那些多年后寻找答案的人来说。

在Outlook 2016中,mailItem.HTMLBody已包含您的默认签名/页脚。

就我而言,我回复了某人。如果你想在之前添加一条消息,请按如下所示操作。易于理解的

MailItem itemObj = item as MailItem; //itemObj is the email I am replying to
var itemReply = itemObj.Reply();
itemReply.HTMLBody = "Your message" + itemReply.HTMLBody; //here happens the magic, your footer is already there in HTMLBody by default, just don't you delete it :)
itemReply.Send();

我也已经处理了几个小时的这个主题。最后,我偶然发现了一个非常有趣的微软支持案例。

https://support.microsoft.com/de-de/help/4020759/text-formatting-may-be-lost-when-editing-the-htmlbody-property-of-an

真正的问题埋在其他地方:Microsoft Outlook使用Microsoft Word作为编辑器。如果在发送项目时Word HTML模块验证了HTML源,则可能会丢失格式。

要解决这个问题,只需加载Word.Interopt并使用Word作为编辑器。

翻译:www.DeepL.com/Translator

    public static void SendMail(string subject, string message, List<string> attachments, string recipients)
    {
        try
        {
            Outlook.Application application = new Outlook.Application();
            Outlook.MailItem mailItem = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
            Word.Document  worDocument = mailItem.GetInspector.WordEditor as Word.Document;
            Word.Range wordRange = worDocument.Range(0, 0);
            wordRange.Text = message;
            foreach (string attachment in attachments ?? Enumerable.Empty<string>())
            {
                string displayName = GetFileName(attachment);
                int position = (int)mailItem.Body.Length + 1;
                int attachType = (int)Outlook.OlAttachmentType.olByValue;
                Outlook.Attachment attachmentItem = mailItem.Attachments.Add
                    (attachment, attachType, position, displayName);
            }
            mailItem.Subject = subject;
            Outlook.Recipients recipientsItems = (Outlook.Recipients)mailItem.Recipients;
            Outlook.Recipient recipientsItem = (Outlook.Recipient)recipientsItems.Add(recipients);
            recipientsItem.Resolve();
            mailItem.Display();
            recipientsItem = null;
            recipientsItems = null;
            mailItem = null;
            application = null;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
    private static string GetFileName(string fullpath)
    {
        string fileName = Path.GetFileNameWithoutExtension(fullpath);
        return fileName;
    }

玩得开心。Thomas

我有一个解决这个问题的变体,值得分享,它完全可以从ANY Outlook帐户发送电子邮件,电子邮件文本与您可以选择的ANY签名合并。

假设:

您添加了对HtmlAgilityPack的引用,该引用用于格式化HTML内容。

由于我找不到任何方法(除了通过注册表)来获得电子邮件帐户签名,这是作为文本值传递的,可以在程序中设置为参数,也可以通过查找Outlook帐户的注册表设置来设置。

发件人帐户是系统上的有效电子邮件帐户签名文件由Outlook使用html格式创建。

我相信在这方面有许多可能的改进。

    /// <summary>
    /// Sends an email from the specified account merging the signature with the text array
    /// </summary>
    /// <param name="to">email to address</param>
    /// <param name="subject">subect line</param>
    /// <param name="body">email details</param>
    /// <returns>false if account does not exist or there is another exception</returns>
    public static Boolean SendEmailFromAccount(string from, string to, string subject, List<string> text, string SignatureName)
    {
        // Retrieve the account that has the specific SMTP address. 
        Outlook.Application application = new Outlook.Application();
        Outlook.Account account = GetAccountForEmailAddress(application, from);
        // check account
        if (account == null)
        {
            return false;
        }
        // Create a new MailItem and set the To, Subject, and Body properties. 
        Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
        // Use this account to send the e-mail. 
        newMail.SendUsingAccount = account;            
        newMail.To = to;
        newMail.Subject = subject;
        string Signature = ReadSignature(SignatureName);
        newMail.HTMLBody = CreateHTMLBody(Signature, text); 
        ((Outlook._MailItem)newMail).Send();
        return true;
    }
    private static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
    {
        // Loop over the Accounts collection of the current Outlook session. 
        Outlook.Accounts accounts = application.Session.Accounts;
        foreach (Outlook.Account account in accounts)
        {
            // When the e-mail address matches, return the account. 
            if (account.SmtpAddress == smtpAddress)
            {
                return account;
            }
        }
        throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
    }
    /// <summary>
    /// Return an email signature based on the template name i.e. signature.htm
    /// </summary>
    /// <param name="SignatureName">Name of the file to return without the path</param>
    /// <returns>an HTML formatted email signature or a blank string</returns>
    public static string ReadSignature(string SignatureName)
    {
        string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "''Microsoft''Signatures";
        string signature = string.Empty;
        DirectoryInfo diInfo = new DirectoryInfo(appDataDir);
        if
        (diInfo.Exists)
        {
            FileInfo[] fiSignature = diInfo.GetFiles("*.htm");
            foreach (FileInfo fi in fiSignature)
            {
                if (fi.Name.ToUpper() == SignatureName.ToUpper()) 
                {
                    StreamReader sr = new StreamReader(fi.FullName, Encoding.Default);
                    signature = sr.ReadToEnd();
                    if (!string.IsNullOrEmpty(signature))
                    {
                        // this merges the information in the signature files together as one string 
                        // with the correct relative paths
                        string fileName = fi.Name.Replace(fi.Extension, string.Empty);
                        signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");
                    }
                    return signature; 
                }
            }
        }
        return signature;
    }
    /// <summary>
    /// Merges an email signature with an array of plain text
    /// </summary>
    /// <param name="signature">string with the HTML email signature</param>
    /// <param name="text">array of text items as the content of the email</param>
    /// <returns>an HTML email body</returns>
    public static string CreateHTMLBody(string signature, List<string> text)
    {
        try
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            HtmlAgilityPack.HtmlNode node;
            HtmlAgilityPack.HtmlNode txtnode;
            // if the signature is empty then create a new string with the text
            if (signature.Length == 0)
            {
                node = HtmlAgilityPack.HtmlNode.CreateNode("<html><head></head><body></body></html>");
                doc.DocumentNode.AppendChild(node);
                // select the <body>
                node = doc.DocumentNode.SelectSingleNode("/html/body");
                // loop through the text lines and insert them
                for (int i = 0; i < text.Count; i++)
                {
                    node.AppendChild(HtmlAgilityPack.HtmlNode.CreateNode("<p>" + text[i] + "</p>"));
                }
                // return the full document
                signature = doc.DocumentNode.OuterHtml;
                return signature;
            }
            // load the signature string as HTML doc
            doc.LoadHtml(signature);
            // get the root node and insert the text paragraphs before the signature in the document
            node = doc.DocumentNode;
            node = node.FirstChild;
            foreach (HtmlAgilityPack.HtmlNode cn in node.ChildNodes)
            {
                if (cn.Name == "body")
                {
                    foreach (HtmlAgilityPack.HtmlNode cn2 in cn.ChildNodes)
                    {
                        if (cn2.Name == "div")
                        {
                            // loop through the text lines backwards as we are inserting them at the top
                            for (int i = text.Count -1; i >= 0; i--)
                            {
                                if (text[i].Length == 0)
                                {
                                    txtnode = HtmlAgilityPack.HtmlNode.CreateNode("<p class='"MsoNormal'"><o:p>&nbsp;</o:p></p>");
                                }
                                else
                                {
                                    txtnode = HtmlAgilityPack.HtmlNode.CreateNode("<p class='"MsoNormal'">" + text[i] + "<o:p></o:p></p>");
                                }
                                cn2.InsertBefore(txtnode, cn2.FirstChild);                                   
                            }
                            // return the full document
                            signature = doc.DocumentNode.OuterHtml;
                        }
                    }
                }
            }
            return signature;
        }
        catch (Exception)
        {
            return "";
        }
    }

要获取/设置用户的默认签名,可以使用windows注册表。Outlook 2010示例:HKEY_CURRENT_USER''Software''Microsoft''Office''14.0''Common''MailSettings姓名:NewSignature数据类型:字符串值:(无结尾的签名文件的名称)

使用GetInspector在使用Inspectors_NewInspector事件实现拦截器时会导致异常。当引发Inspectors_NewInspector事件时,您还会发现签名尚未添加到MailItem。

如果您用自己的代码(例如您自己的按钮)触发Item.Send(),则"签名"answers"内容结束"都将有一个锚定标记<a>。请注意,如果您自己处理Outlook功能区[发送]按钮单击事件(对于外接程序来说很常见),这些标记将从HTMLBody中删除(在从Word HTML到HTML的翻译中)。

我的解决方案是处理Item.Open事件,以便在创建/引发Interceptor/IInspectors_NewInspector时,我可以向包含的<p>标记添加一个Id属性,以便稍后发送时使用。即使在发送之后,该属性也会保留在HTML中。

这确保了无论何时调用Send,我都可以在代码中检测到"签名"或"内容结束"段落。