Classe C # SmtpClient non in grado di inviare e-mail utilizzando gmail
-
19-09-2019 - |
Domanda
Ho problemi l'invio di email utilizzando il mio account Gmail. Im tirando fuori i miei capelli.
Le stesse impostazioni funzionano bene in Thunderbird.
Ecco il codice. Ho anche provato porta 465 senza fortuna.
SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.Credentials = new NetworkCredential("username", "pass");
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
MailMessage mm = new MailMessage("donotreply@domain.com", "destination@domain.com", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);
Ecco l'errore
"Il server SMTP richiede una connessione sicura o il client non è stato autenticato Risposta del server:. 5.5.1 autenticazione richiesta saperne di più a"
Ecco l'analisi dello stack
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at email_example.Program.Main(String[] args) in C:\Users\Vince\Documents\Visual Studio 2008\Projects\email example\email example\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Soluzione
Non credere quello che risolto il mio problema.
La proprietà Credenziali
ss.Credentials = new NetworkCredential("username", "pass");
deve essere dichiarato dopo il
ss.UseDefaultCredentials = false;
Quindi, la quotazione finale codice di lavoro è
SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential("username", "pass");
MailMessage mm = new MailMessage("donotreply@domain.com", "destination@domain.com", "subject here", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.Send(mm);
Questo è un bug?
Altri suggerimenti
Nel tuo caso significa che dovete inviarlo con l'indirizzo email che hai eseguito l'accesso a Google con.
Quindi forse c'è un firewall che interferisce con la connessione. Sto incontrando questo problema in questo momento durante il test il codice. Prova il suggerito TELNET-Test.
Il lavoro per me solo con la porta 25.
Questo funziona, ma non è molto le prestazioni amichevole. Partenza client.SendAsync: http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx
Un esempio di caso di utilizzo:
var message = new MailMessage("from", "to", "subject", "body");
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("login", "password"),
EnableSsl = true
};
client.SendCompleted += (s, e) =>
{
client.Dispose();
message.Dispose();
};
client.SendAsync(message, null);
di questo lavoro perfettamente.
Creare un modello di posta in un file separato MailTemplate.html
.
Aggiungi NetworkCredentials genuini - login e password
private void SendMail()
{
string filename = Server.MapPath("~/MailTemplate.html");
string username = UserName.Text.ToString();
string mailbody = System.IO.File.ReadAllText(filename);
mailbody = mailbody.Replace("##NAME##", username);
string to = Email.Text;
string from = "test@gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Auto Response Email";
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("test@gmail.com", "test123#");
client.EnableSsl = true;
client.UseDefaultCredentials = true;
client.Credentials = basicCredential;
try
{
client.Send(message);
SuccessMessage.Text = "Email Sending successfully";
}
catch (Exception ex)
{
ErrorMessage.Text = ex.Message.ToString();
}
}
MailTemplate.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
</head>
<body>
<div style="border: thin solid #0066FF; width: 550px; margin: 25px auto; padding: 15px; font-family: 'Microsoft Himalaya'; font-size: x-large; font-style: normal; color: #0066FF; background-color: #EfEFF2;">
<br />
<p style="vertical-align: middle">Dear ##NAME##,</p>
</div>
</body>
</html>
posso verificare che l'impostazione useDefaultCredentials false deve essere fatto prima della creazione della NetworkCredentials. Ho avuto lo stesso problema.
Funziona bene nel mio caso:
private void btnTestConnection_Click(object sender, EventArgs e)
{
btnTestConnection.Enabled = false;
SmtpClient ss = new SmtpClient(txtSmtpHostName.Text.Trim(), Convert.ToInt32(numSmtpHostPort.Value));
ss.EnableSsl = chkSmtpSecureType.Checked;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential(txtSmtpAccount.Text.Trim(), txtSmtpPassword.Text);
MailMessage mm = new MailMessage(txtSmtpFromEmail.Text.Trim(), "test@domain.com", "subject", "my body");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
ss.SendCompleted += (s, b) =>
{
ss.Dispose();
mm.Dispose();
};
try
{
ss.Send(mm);
ss.Dispose();
mm.Dispose();
MessageBox.Show("Connection successfully");
}
catch (Exception ep)
{
MessageBox.Show("Connection error: " + ep.Message, "Smtp Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
btnTestConnection.Enabled = true;
}