Send email with attachment

In this article we’ll create and send email with an attachment.

As a prerequisite you need to add reference to Mail.dll .NET email component to your project.

We’ll use MailBuilder class to create email message. This will be plain text message sent from Alice to Bob:

MailBuilder builder = new MailBuilder();
builder.From.Add(new MailBox("alice@mail.com", "Alice"));
builder.To.Add(new MailBox("bob@mail.com", "Bob"));
builder.Subject = "Test";
builder.Text = "This is plain text message.";

You use AddAttachment method to add new attachment to the email, it returns MimeData class instance, that can by used to change/set file name, data, content-id, or any other MIME header. This method has 3 overloads, that allow to create and add attachment from file, byte array or add existing MimeData object as email attachment. In our sample we’ll create attachment from file located on disk.

MimeData attachment = builder.AddAttachment(@"../image.jpg");

Mail.dll email component automatically recognizes content type using file extension. When you create attachment using byte array or MemoryStream, you can use ContentType property to set it manually:

attachment.ContentType = ContentType.ImageJpeg;

Finally we’ll use Smtp component to connect to SMTP server and send your message.

Following is the entire sample, that creates new email message, adds attachment from file located on disk. Than it connects to specified SMTP server and sends the message. Please note that some error handling is missing for simplicity and you should examine ISendMessageResultresult object returned by SendMessage to be sure that email sending was successful.

// C# version

using System;
using Limilabs.Mail;
using Limilabs.Mail.Headers;
using Limilabs.Client.SMTP;

class Program
{
    static void Main(string[] args)
    {
        // Use builder class to create new email message
        MailBuilder builder = new MailBuilder();
        builder.From.Add(new MailBox("alice@mail.com", "Alice"));
        builder.To.Add(new MailBox("bob@mail.com", "Bob"));
        builder.Subject = "Test";
        builder.Text = "This is plain text message.";

        // Read attachment from disk, add it to Attachments collection
        MimeData attachment = builder.AddAttachment(@"../image.jpg");

        IMail email = builder.Create();

        // Send the message
        using (Smtp smtp = new Smtp())
        {
            smtp.Connect("server.example.com");   // or ConnectSSL for SSL
            smtp.UseBestLogin("user", "password");   // remove if not needed

            smtp.SendMessage(email);

            smtp.Close();
        }

    }
};
' VB.NET version

Imports Limilabs.Client.SMTP
Imports Limilabs.Mail
Imports Limilabs.Mail.MIME
Imports Limilabs.Mail.Headers

Public Module Module1
    Public Sub Main(ByVal args As String())

        ' Use builder class to create new email message
        Dim builder As New MailBuilder()
        builder.From.Add(New MailBox("alice@mail.com", "Alice"))
        builder.[To].Add(New MailBox("bob@mail.com", "Bob"))
        builder.Subject = "Test"
        builder.Text = "This is plain text message."

        ' Read attachment from disk, add it to Attachments collection
        Dim attachment As MimeData = builder.AddAttachment("../image.jpg")

        Dim email As IMail = builder.Create()

        ' Send the message
        Using smtp As New Smtp()
            smtp.Connect("server.example.com")    ' or ConnectSSL for SSL
            smtp.UseBestLogin("user", "password")   ' remove if not needed

            smtp.SendMessage(email)

            smtp.Close()
        End Using
    End Sub
End Module

Tags:     

Questions?

Consider using our Q&A forum for asking questions.

5 Responses to “Send email with attachment”

  1. Peter Steiness Says:

    How do I convert a System.Net.Mail.Attachment object to a Limilabs.Mail.MIME.MimeData object?

    ContentStream = Stream object.
    Filename = String object.
    ContentType = String object.

    -Peter Steiness
    NOVAQ – Qmanager.dk licens.

  2. Limilabs support Says:

    Peter,

    As you might expect there is no direct conversion method.
    You need to have data as byte array, ContentType object (you can parse it from string) and file name:

    byte[] data = ...;
    string contentType = ...;
    string fileName = ...;
    
    MimeData mime = new MimeFactory().CreateMimeData();
    mime.Data = data;
    mime.ContentType = ContentType.Parse(contentType);
    mime.FileName = fileName;
    
  3. Limilabs support Says:

    @Peter,

    You can catch the exception thrown by Connect method.

  4. Tony Says:

    Hi,

    I have an app that I am creating (C#, XAML). I have a .csv file that my app created and stores it in the following location:

    StringBuilder tempFileName = new StringBuilder();
    tempFileName.Append(ApplicationData.Current.LocalSettings.Values[“lastName”].ToString()).Append(“_”)
    .Append(ApplicationData.Current.LocalSettings.Values[“firstName”].ToString()).Append(” – (“)
    .Append(txtEventName.Text).Append(“).csv”);

    Then I tried to attach this file to the email:
    MimeData attachment = builder.AddAttachment(tempFileName);
    attachment.ContentType = ContentType.TextPlain;

    It is giving me an error. What am I doing wrong. I looked at the sample and did exactly what it says.

    Thank you.

  5. Limilabs support Says:

    @Tony,

    What kind of error are you getting? What is the message, type, stack trace?

    Are you sure that there exists a file at the location you specify?
    You can use File.Exists to check.

    Also there is no MailBuilder.AddAttachment overload that takes StringBuilder class as a parameter, did you meant:
    builder.AddAttachment(tempFileName.ToString())?