Search code examples
smtpemail-attachmentsemailsmtpclientmailmessage

How can I add an attachment to a MailMessage?


I've got this code that sends a simple email using SmtpClient, MailMessage, and MailAddress objects:

private void EmailMessage(string msg)
{
    string TO_EMAIL = "[email protected]";
    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);
    }
}

I also need, though, to attach a file to an email. I was doing it using Outlook like so:

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

...but I need to move away from using Outlook for this. Here the MailItem is a Microsoft.Office.Interop.Outlook.MailItem

How can I add attachments in the simple MailMessage I need to use now?

Setting the Importance is not too important, I don't think, but the Display is something I will need to set for the MailMessage, too.


Solution

  • Easy:

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