Uploading emails using IMAP

Uploading emails in .NET to the IMAP server is fairly easy with Mail.dll IMAP library for .NET

Uploading new email to IMAP

First sample shows how to create new email message and upload it to specified IMAP folder. As usual we’ll be using MailBuilder class to create new email. It’s going to be a simple text message from Alice to Bob:

MailBuilder builder = new MailBuilder();
builder.Subject = "subject";
builder.From.Add(new MailBox("alice@email.com", "Alice"));
builder.To.Add(new MailBox("bob@email.com", "Bob"));
builder.Text = "This is plain text email";
IMail email = builder.Create();

Next we’ll connect to IMAP server and upload this email. Of course you can send this email before uploading.

using (Imap imap = new Imap())
{
    imap.Connect("imap.example.com");    // or ConnectSSL for SSL
    imap.UseBestLogin("user", "password");

    // The name of the folder depends on your IMAP server
    imap.UploadMessage("[Gmail]/Sent Mail", email);

    imap.Close();
}

You may choose any folder for your upload. However in the most common scenario, you’ll want to upload message to the Sent folder. If your server supports XLIST, SPECIAL-USE extension or at least follow common naming conventions CommonFolders may help you:

CommonFolders folders = new CommonFolders(imap.GetFolders());
imap.UploadMessage(folders.Sent, email);

Here you can find more details on obtaining common IMAP folders

Here’s the VB .NET version of the above code:

' VB.NET code

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

Dim email As IMail = builder.Create()

Using imap As New Imap()
	imap.Connect(""imap.example.com")    ' or ConnectSSL for SSL
	imap.UseBestLogin("user", "password")

	' The name of the folder depends on your IMAP server
	imap.UploadMessage("[Gmail]/Sent Mail", email)

	imap.Close()
End Using

Uploading existing email to IMAP

In the second example we’ll upload an existing email in eml format from disk to the IMAP server in .NET.

*.eml extension is a standard extension used for storing emails. Eml file contains raw data received from IMAP or POP3 server. You can use GetMessageByUID on Pop3 or Imap class to obtain those data. It can be also created using IMail.Render method.

Eml file includes, email message body in plain text, HTML (if defined) formats, all email headers (such as: from, to, subject, date and so on), and all visual elements and all attachments.

// C# code

using (Imap imap = new Imap())
{
    imap.Connect("server");  // or ConnectSSL for SSL
    imap.Login("user", "password");

    byte[] eml = File.ReadAllBytes("email.eml");

    // The name of the folder depends on your IMAP server
    imap.UploadMessage("[Gmail]/Sent Mail", eml);

    imap.Close();
}
' VB.NET code

Using imap As New Imap()
	imap.Connect("server")  ' or ConnectSSL for SSL
	imap.Login("user", "password")

	Dim eml As Byte() = File.ReadAllBytes("email.eml")

	' The name of the folder depends on your IMAP server
	imap.UploadMessage("[Gmail]/Sent Mail", eml)

	imap.Close()
End Using

Please note that only few IMAP servers are going to send the message to the actual recipients when it is uploaded. Most servers will only store the message without sending it. You should use SMTP protocol to send email before uploading.

Tags:     

Questions?

Consider using our Q&A forum for asking questions.

15 Responses to “Uploading emails using IMAP”

  1. Roberto Says:

    Hello,
    I try to submit an email, through this method, with many attachments (total size approx. 19MB) and I jump an error: “Unable to write data to the transport connection: An error occurred during connection attempt because the connected party did not properly respond after a period of time, or failed to established connection and connected host has failed to respond. ”
    You know that it can be? The mail then you are on gmail.
    Thanks

  2. Limilabs support Says:

    @Roberto,
    1.
    Uploading message to IMAP server is a different thing than sending email.
    You should use SMTP server if you want to send an email.

    2.
    I don’t know how your code looks like, you might have simply reached Gmail’s 25MB message limit.
    (Typically, encoding makes the size of the files grow slightly 19 * 1,33 = 25,27)

    3.
    Could you please contact us directly, and provide a bit more info (code, stack trace, log)

    [Edit]
    In fact I was able to upload 10MB, 15MB, 18 MB and 19MB messages.
    With 19MB Gmail randomly disconnected without any error message.
    Seems it’s their bug.

  3. Daryl Says:

    Hello,
    vb.net 2010

    I want to upload an email using imap but mark it as unread

    imap.UploadMessage("Inbox", builder2.Create())
    

    works as described

    BUT

    Dim messageinfo As New Limilabs.Client.IMAP.UploadMessageInfo
    messageinfo.Flags.Add(Limilabs.Client.IMAP.Flag.Unseen)
    imap.UploadMessage("Inbox", builder2.Create(),messageinfo)
    

    gives the error:


    Expected more data request, but received: e9f70402ea13473e BAD APPEND

    Any help would be appreciated – thanks

  4. Limilabs support Says:

    @Daryl

    Most likely Unseen flag can not by used in this way by your IMAP server.

    Some server accepts negative flags in this context (hMailServer) others don’t (Gmail).

    Please simply remove messageinfo.Flags.Add(Limilabs.Client.IMAP.Flag.Unseen) line:

    Dim messageinfo As New Limilabs.Client.IMAP.UploadMessageInfo
    imap.UploadMessage(“Inbox”, builder2.Create(),messageinfo)
    

    It should work as expected.

  5. Michael Says:

    Hi,

    If I use Mail.dll Smtp to send email (using fluent interface or not) and want a “copy” of the message placed in the online mail client (e.g. Gmail) sent mail folder, is it safe to use Imap.UploadMessage for this, or do I risk the message being sent twice? Once by using Smtp and once when uploading the message like this (where some Imap servers apparently decide to also send the message).

    Thanks,
    Michael

  6. Limilabs support Says:

    @Michael,

    By default, uploading to ‘sent’ folder should not send the message. RFC3501 is very precise about this “The APPEND command is not used for message delivery, because it does not provide a mechanism to transfer [SMTP] envelope information.”

  7. Michael Says:

    Ok, I see. Thanks. I also found that sending through Gmails SMTP server did the “copying” to the sent messages folder automatically, so no problem there.

  8. Limilabs support Says:

    @Michael,

    You are right: when you send an email using Gmail’s SMTP server it automatically appears in “Sent Mail” folder.

  9. Bruno Says:

    I have successfully uploaded emails to my GMail inbox using the code above, but I haven’t yet been able to apply GMail labels during the upload. Could you help me out?
    Thanks,
    Bruno.

  10. Limilabs support Says:

    @Bruno,

    You can apply Gmail labels using Imap.GmailLabelMessageByUID method:

    long uploaded = (long)client.UploadMessage("INBOX", email);
    imap.GmailLabelMessageByUID(uploaded, 
        new List<string> { @"\Starred", "My label"});
    

    References: Label message with Gmail system label, Label message with Gmail label.

  11. Bruno Says:

    Thanks! That worked beautifully.

  12. Benjamin Graf Says:

    I wrote a short program that downloads the mails from one server to upload them on another server.
    But sometimes when the attachment of the mail is greater than 2MB the upload to the new server fails. I create the mail from an eml file. Is there a known workaround to avoid that error?

  13. Limilabs support Says:

    @Benjamin,

    Most likely this server refuses messages bigger than that size.
    Please also disable your antivirus software as it may be the cause of your problems.

    What is the exact error message/exception type/stacktrace?

  14. Curious Says:

    How do you know if the server creates a copy of the message and places it in sent items automatically when you use limilabs SMTP send ?

    I want to know if there is a need to upload my message or not in the sent items folder .

    Thanks a lot !

  15. Limilabs support Says:

    @Curious,

    It depends on the server, and unfortunately there is no IMAP or SMTP protocol extension, that would allow to check, if the server does that.