zoukankan      html  css  js  c++  java
  • Send an email with format which is stored in a word document

    1. Add a dll reference: Microsoft.Office.Interop.Word.dll

    2. Add the following usings 

    using Word = Microsoft.Office.Interop.Word;
    using System.Net.Mail;
    using System.Text.RegularExpressions;

    3. Paste the following code into your application and call it.

    Note: Please modify the email info, and put a word file with your email body.

    private void SendEmailWithFormat()
    {
    Word.Application myWord = new Word.Application();
    Word.Document doc = new Word.Document();
    object unknow = Type.Missing;

    try
    {
    string fileLocation = Application.StartupPath +@"EmailBody.docx";
    doc.Activate();
    doc = myWord.Documents.Open(fileLocation,ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
    ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
    doc.ActiveWindow.Selection.WholeStory();
    doc.ActiveWindow.Selection.Copy();
    doc.ActiveWindow.Visible = false;

    IDataObject data = Clipboard.GetDataObject();
    string fileContentInHtmlFormat = data.GetData(DataFormats.Html).ToString();

    string body = "<html " + Regex.Split(fileContentInHtmlFormat, "<html", RegexOptions.IgnoreCase)[1];

    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

    mail.From = new MailAddress("your gmail account");
    mail.To.Add("send to email account");
    mail.Subject = "Test Mail";
    mail.Body = body;

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your gmail account", "password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);
    MessageBox.Show("Mail Has Been Sent Out Successfully!","Successfully");
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.ToString());
    }
    finally
    {
    doc.Close(ref unknow, ref unknow, ref unknow);
    myWord.Quit(ref unknow, ref unknow, ref unknow);
    }
    }

  • 相关阅读:
    设计模式的分类
    SQL Server 2005 TSQL 学习笔记:排名函数
    JS正则表达式语法
    魅族 “拜产品教”公司的优秀与局限
    jqueryMobile初始化组件
    Loading Scripts Without Blocking
    LabJs学习笔记:分析图
    翻转的css3样式
    IE(IE6/IE7/IE8)支持HTML5标签
    我的空间轨迹!
  • 原文地址:https://www.cnblogs.com/Lihao2013/p/3544385.html
Copyright © 2011-2022 走看看