如何向MailMessage添加附件?

时间:2017-03-14 22:49:41

标签: smtp email-attachments email-integration smtpclient mailmessage

我有这个代码使用SmtpClient,MailMessage和MailAddress对象发送一个简单的电子邮件:

private void EmailMessage(string msg)
{
    string TO_EMAIL = "cshannon@proactusa.com";
    var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
    string userName = windowsIdentity.Name;
    string subject = string.Format("Log msg from Report Runner app sent {0}; user was {1}", DateTime.Now.ToLongDateString(), userName);
    string body = msg;

    var SmtpServer = new SmtpClient(ReportRunnerConstsAndUtils.EMAIL_SERVER);
    var SendMe = new MailMessage();
    SendMe.To.Add(TO_EMAIL);
    SendMe.Subject = subject;
    SendMe.From = new MailAddress(ReportRunnerConstsAndUtils.FROM_EMAIL);
    SendMe.Body = body;
    try
    {
        SmtpServer.UseDefaultCredentials = true;
        SmtpServer.Send(SendMe);
    }
}

但是,我还需要将文件附加到电子邮件中。我是这样使用Outlook的:

Application app = new Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
. . .
FileInfo[] rptsToEmail = GetLastReportsGenerated();
foreach (var file in rptsToEmail)
{
    String fullFilename = String.Format("{0}\\{1}", uniqueFolder, file.Name);
    if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
    {
        mailItem.Attachments.Add(fullFilename);
    }
}
mailItem.Importance = OlImportance.olImportanceNormal;
mailItem.Display(false);

...但我需要放弃使用Outlook。这里的MailItem是一个Microsoft.Office.Interop.Outlook.MailItem

如何在我现在需要使用的简单MailMessage中添加附件?

设置重要性不是太重要,我不这么认为,但显示也是我需要为MailMessage设置的。

1 个答案:

答案 0 :(得分:-3)

易:

if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
    var attachment = new Attachment(fullFilename);
    mailMsg.Attachments.Add(attachment);
}
mailMsg.Priority = MailPriority.Normal;