将Word文档作为电子邮件发送

时间:2013-06-21 17:46:54

标签: c# .net email ms-word

在Microsoft Word 2007中,可以将文档作为电子邮件正文发送;文字,图片和格式。有没有办法在C#中使用Word的“发送邮件到收件人”选项?如果有可能我该怎么做呢? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

您需要编写Microsoft Word插件才能执行此操作。对于此检查微软网站的基础:Word solutions with Visual Studio

你可以做下面的事情来解决你的问题。保存文档时,代码将发送邮件。有了一个单词addin你有很多事件你可以cacth和做自己的东西。或者,如果要通过单击按钮发送邮件,则可以添加自己的按钮。

void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.DocumentBeforeSave += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(DocumentSave);
}

void DocumentSave(Word.Document doc, ref bool test, ref bool test2)
{
    if(doc is Word.Document)
    {                
        SendMailWithAttachment(doc);
    }
}

public void SendMailWithAttachment(Word.Document doc)
{
    SmtpClient smtpClient = new SmtpClient();
    NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
    MailMessage message = new MailMessage();
    MailAddress fromAddress = new MailAddress(MailConst.Username);

    // setup up the host, increase the timeout to 5 minutes
    smtpClient.Host = MailConst.SmtpServer;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = basicCredential;
    smtpClient.Timeout = (60 * 5 * 1000);

    message.From = fromAddress;
    message.Subject = subject;
    message.IsBodyHtml = false;
    message.Body = body;
    message.To.Add(recipient);

    var attachmentFilename = doc.FullName

    if (attachmentFilename != null)
    {
        Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
        ContentDisposition disposition = attachment.ContentDisposition;
        disposition.CreationDate = File.GetCreationTime(attachmentFilename);
        disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
        disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
        disposition.FileName = Path.GetFileName(attachmentFilename);
        disposition.Size = new FileInfo(attachmentFilename).Length;
        disposition.DispositionType = DispositionTypeNames.Attachment;
        message.Attachments.Add(attachment);                
    }

    smtpClient.Send(message);
}