Send an email with format which is stored in a word document

时间:2022-10-27 15:28:04

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