#c# #email #smtpclient
#c# #Адрес электронной почты #smtpclient
Вопрос:
Я пытаюсь отправить электронное письмо из моего приложения c # WinForms, используя SMTP-сервер g-mail. Вот мой код:
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)rn at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)rn at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)rn at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)rn at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)rn at System.Net.Mail.SmtpClient.GetConnection()rn at System.Net.Mail.SmtpClient.Send(MailMessage message)"
TargetSite: {Int32 ProcessRead(Byte[], Int32, Int32, Boolean)}
Я понимаю, что это, вероятно, снова будет помечено как дубликат, поскольку об этом, вероятно, спрашивали раньше, но ничто из того, что я прочитал, не решит мою проблему.
Кстати: я настроил свои настройки Google так, чтобы разрешать небезопасные приложения.
Комментарии:
1. Есть что-то,
null
чего не должно бытьnull
. Какая строка вызывает ошибку? Эта строка должна бытьnull
? Если нет, убедитесь, что вы это изменили.2. Ошибка не выдается, пока не достигнет события SendCompletedCallback
3. Я использую SecureString только для пароля SecureString.
4. @RickInWestPalmBeach Разве вы не должны ожидать этого:
smtp.SendAsync(msg, msg);
посколькуawait smtp.SendAsync(msg, msg);
5. @RyanWilson Нет, SmtpClient предшествует асинхронному шаблону на основе задач.
SendAsync
возвращает пустоту. ОднакоSendMailAsync
возвращает задачу, и ее можно ожидать.
Ответ №1:
Мы видим, что настоящая ошибка здесь:
net_io_connectionclosed
Это означает, что GMail отклоняет ваше соединение.
Это ожидаемо.
GMail больше не принимает обычную аутентификацию для SMTP-соединений по умолчанию!
Этого не было уже несколько лет.
Если вы хотите использовать GMail в качестве традиционного SMTP-сервера, вы должны выполнить одно из трех действий:
- Включите двухфакторную аутентификацию и настройте пароль для каждого приложения
или
- Поддержка аутентификации OAuth
или
- Включить менее безопасные приложения
Если вы не выполните одно из этих действий, GMail отклонит ваши SMTP-соединения.
Комментарии:
1. Как указано выше, я уже включил «Менее безопасные приложения», и я все еще получаю ту же ошибку.