Я пытаюсь отправить электронное письмо из моего приложения c # WinForms, используя почтовый SMTP-сервер.Вот мой код:
string fromEmail = txtFromEmail.Text.Trim();
string toEmail = txtToEmail.Text.Trim();
string[] toArray = toEmail.Split(',');
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromEmail);
for (int i = 0; i <= toArray.Length - 1; i++)
{
msg.To.Add(toArray[i]);
}
msg.Subject = "Test E-mail";
msg.Body = "This is a test";
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
msg.HeadersEncoding = Encoding.GetEncoding(1252);
msg.SubjectEncoding = Encoding.GetEncoding(1252);
msg.BodyEncoding = Encoding.GetEncoding(1252);
AlternateView av1 = AlternateView.CreateAlternateViewFromString(msg.Body, null, System.Net.Mime.MediaTypeNames.Text.Html);
msg.AlternateViews.Add(av1);
smtp = new SmtpClient();
smtp.Host = txtSMTPServer.Text.Trim();
smtp.UseDefaultCredentials = false;
NetworkCredential cred = new NetworkCredential();
SecureString ss = new NetworkCredential("", txtSMTPPassword.Text.Trim()).SecurePassword;
cred.UserName = txtSMTPUsername.Text.Trim();
cred.SecurePassword = ss;
smtp.Credentials = cred;
smtp.EnableSsl = chkEnableSSL.Checked;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Port = Convert.ToInt16(txtSMTPPort.Text.Trim());
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtp.SendAsync(msg, msg);
Я получаю следующее сообщение об ошибке:
'e.Error.InnerException.Message' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: "8a9e67622e334c659c856a023d4b1631"
StackTrace: " at <>x.<>m0(frmSettings <>4__this, Object sender, AsyncCompletedEventArgs e)"
TargetSite: {System.String <>m0(Ariba.frmSettings, System.Object, System.ComponentModel.AsyncCompletedEventArgs)}
Я могу отправлять электронную почту с SMTP-сервера, не входящего в Gmail.Чего мне не хватает?
С тех пор я изменил свой метод отправки на синхронный, используя smtp.Send (msg), но теперь я получаю другую ошибку:
{"Unable to read data from the transport connection: net_io_connectionclosed."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232800
HelpLink: null
InnerException: null
Message: "Unable to read data from the transport connection: net_io_connectionclosed."
Source: "System"
StackTrace: " at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)"
TargetSite: {Int32 ProcessRead(Byte[], Int32, Int32, Boolean)}
Я понимаю, что это будетвозможно, снова будут помечены как дубликаты, поскольку об этом, возможно, уже спрашивали ранее, но ничего из того, что я прочитал, не решит мою проблему.
Кстати: я установил свои настройки Google, чтобы разрешить использование незащищенных приложений.