I have some older code that works fine for sending emails, but visual studio tells me that the code is obsolete and I should change it over to Net.Mail
from Web.Mail
. I have rewritten most of it, but I have a few questions.
Here is the original, working code:
public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
var mailMessage = new MailMessage
{
From = from,
To = to,
Subject = subject,
Body = body,
BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
};
// Add attachments
if (attachments != null)
{
foreach (var t in attachments)
{
mailMessage.Attachments.Add(new Attachment(t));
}
}
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString(CultureInfo.InvariantCulture));
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
SmtpMail.SmtpServer = _smtp;
SmtpMail.Send(mailMessage);
}
And here is the rewritten portion (well, sort of):
public void Send2(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
var fromObj = new MailAddress(from);
var toObj = new MailAddress(to);
var mailMessage = new System.Net.Mail.MailMessage
{
From = fromObj,
Subject = subject,
Body = body,
IsBodyHtml = isHtml,
};
mailMessage.To.Add(toObj);
if (attachments != null)
{
foreach(var t in attachments)
{
mailMessage.Attachments.Add(new Attachment(t));
}
}
var smtp = new SmtpClient(_smtp) {Credentials = new NetworkCredential(_accountName, _password), Port = _port, EnableSsl = true};
smtp.Send(mailMessage);
}
In case you were wondering, I have _port
and _smtp
set higher up in the code, 465 and smtp.gmail.com respectively.
So it seems to work, but then gets down to the sending part and spits out one of these:
System.Net.Mail.SmtpException: The operation has timed out.
Is there something I am missing, like from the Fields
in the original code, that is causing it to timeout?
Thanks!
SOLUTION
Thanks to DavidH's point in the right direction, the port needs to be changed from 465 to 587 (or 25; I am using the former with no problem).
A little Google goes a long way. Check this answer for your cure - you're using the wrong port:
https://stackoverflow.com/a/11244548/2420979