public async Task SendMail() {
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Pablo", "pablo@gmail.com"));
message.To.Add(new MailboxAddress("Julio", "julio@hotmail.com"));
message.Subject = "We keep spending most of our lives living in the gangsta's paradise";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart("plain") {
Text = "Hi there, this is a body of the message."
};
MemoryStream myImageStream = convertBMPImageToStream(bmpImage);
var attachment = new MimePart("image", "jpg") {
ContentObject = new ContentObject(myImageStream, ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = "attachedImage.jpg",
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart("mixed");
multipart.Add(body);
multipart.Add(attachment);
message.Body = multipart;
using(var client = new SmtpClient()) {
client.Connect("smtp.gmail.com", 587, false);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("gmailUsername", "gmailpassword");
try {
await client.SendAsync(message);
} catch (SmtpCommandException ex) {
Console.WriteLine("Error sending message: {0}", ex.Message);
Console.WriteLine("\tStatusCode: {0}", ex.StatusCode);
switch (ex.ErrorCode) {
case SmtpErrorCode.RecipientNotAccepted:
Console.WriteLine("\tRecipient not accepted: {0}", ex.Mailbox);
break;
case SmtpErrorCode.SenderNotAccepted:
Console.WriteLine("\tSender not accepted: {0}", ex.Mailbox);
break;
case SmtpErrorCode.MessageNotAccepted:
Console.WriteLine("\tMessage not accepted.");
break;
}
} catch (SmtpProtocolException ex)
Console.WriteLine("Protocol error while sending message: {0}", ex.Message);
client.Disconnect(true);
}
}