Reputation: 4889
public static string Send(string to, string subject, string content, string from = "")
{
try
{
MimeMessage message = new MimeMessage();
message.Subject = subject;
message.Body = new TextPart("Plain") { Text = content };
message.From.Add(new MailboxAddress(from));
message.To.Add(new MailboxAddress(to));
SmtpClient smtp = new SmtpClient();
smtp.Connect(
"smtp.live.com"
, 587
, MailKit.Security.SecureSocketOptions.StartTls
);
smtp.Authenticate("[email protected]", "Password");
smtp.Send(message);
smtp.Disconnect(true);
return "Success";
}
catch (Exception ex)
{
return $"Failed. Error: {ex.Message}";
}
}
using gmail
smtp.Connect(
"smtp.gmail.com"
, 587
, MailKit.Security.SecureSocketOptions.StartTls
);
I tried modify some properties that from other website's articles.
But, I usually get these error messages:
"Failed. Error: The SMTP server does not support authentication."
"Failed. Error: The remote certificate is invalid according to the validation procedure."
How to set the properties correctly?
Upvotes: 3
Views: 7614
Reputation: 732
I use MimeKit in ASP Core to send to Gmail. Here is a snippet from my project that works for me:
using (var client = new SmtpClient())
{
client.Connect(_appSettings.SmtpServerAddress, _appSettings.SmtpServerPort, SecureSocketOptions.StartTlsWhenAvailable);
client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP
client.Authenticate(_appSettings.SmtpServerUser, _appSettings.SmtpServerPass);
client.Send(Email);
client.Disconnect(true);
}
Upvotes: 5