Creating messages

In certain situations, when you are using the standard System.Net.Mail.SmtpClient class to send messages, you need to additionally store the sent message in the Sent folder on your server. In this case, you can make use of the Folder.AppendMessage method. It can also be used to upload EML data to server to create messages.

Uploading a message sent with System.Net.Mail.SmtpClient

// A method for sending messages
public MailMessage SendMail(string server, string login, string password, string from, string to, string subject, string text)
{
	try
	{
		MailMessage mail = new MailMessage();
		mail.From = new MailAddress(from);
		mail.To.Add(new MailAddress(to));
		mail.Subject = subject;
		mail.Body = text;

		SmtpClient client = new SmtpClient();
		client.Host = smtpServer;
		client.Port = 587;
		client.EnableSsl = true;
		client.Credentials = new NetworkCredential(login, password);
		client.DeliveryMethod = SmtpDeliveryMethod.Network;
		client.Send(mail);

		return mail;
	}
	catch (Exception e)
	{
		throw new Exception("Mail.Send: " + e.Message);
	}
}


var imapClient = new ImapClient("imap.gmail.com", true);

if(imapClient.Connect()) {
     
     if(imapClient.Login("address@gmail.com", "password")) {
        
        // Sending a message
     	var newMsg = SendMail(
     		"smtp.gmail.com",
     		"address@gmail.com",
     		"password",
     		"address@gmail.com",
     		"friend@gmail.com",
     		"Test Message",
     		"Hello my friend, this is a test message"
     	);

     	// Uploading the sent message to the Sent folder
     	imapClient.Folder.Sent.AppendMessage(newMsg);

     }
}
else {
     // connection not successful
}

If you want to the client to additionally add some flags for the message, or change the internal date which will be used for the message, just pass the required information in the other two parameters of the AppendMessage method:

imapClient.Folder.Sent.AppendMessage(newMsg, new[]{ MessageFlags.Flagged }, DateTime.Now);

Next

Last edited Apr 14, 2015 at 6:29 PM by pavel_azanov, version 2