I can't understand why this code is not working.
I have this error:
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.Read ()
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.SendCore
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.SendInternal
System.IO.IOException: Connection closed
at System.Net.Mail.SmtpClient.Send
static void Main(string[] args)
{
var smtp = new SmtpClient
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true,
Host = "smtp.gmail.com",
//465 SSL se uso 25 solo ad utenti google mando
Port = 465,
Credentials = new NetworkCredential("id", "password"),
};
Console.WriteLine("Mail From: ");
var fromAddress = new MailAddress(Console.ReadLine());
Console.WriteLine("Mail To: ");
var toAddress = new MailAddress(Console.ReadLine());
Console.WriteLine("Subject: ");
string subject = Console.ReadLine();
Console.WriteLine("Body: ");
string body = Console.ReadLine();
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
try
{
smtp.Send(message);
}
catch(Exception ex)
{
Console.WriteLine("Unable to send message due to the following reason: " + ex.ToString());
}
}
how can I solve these problems?
Try port 587 instead of 465. Port 465 is technically deprecated.
from the OP's comment:
Even if I set the port on 587 I have the same errors. In addition, Gmail tells me that someone attempted to access my account
If that's the case when you are using port 587 then you should allow less secure applications in your gmail settings. If you are using 2 factor authentication then you also need to add an application password and use that instead.
Related
I am sending emails from a C# method, where from one moment to another it stops working and I allow access to my host.
I have not uploaded changes to production, for a long time and I have even less touched this part of the code. I get the following error but I don't know what it means and what solution to give about it:
Error: IoException:
Handshake failed due to unexpected packet format
Code:
string mailFrom = emailSettings.Correo;
string nameFrom = emailSettings.Nombre;
string passwordFrom = emailSettings.Password;
string hostSMTP = emailSettings.HostSMTP;
// Message data
MailAddress fromAddress = new MailAddress(mailFrom, nameFrom, Encoding.UTF8);
MailAddress toAddress = new MailAddress(mailDestino, nombreDestinatario, Encoding.UTF8);
// Specify the message content.
using (MailMessage message = new MailMessage(fromAddress, toAddress)
{
Subject = asuntoMensaje,
SubjectEncoding = Encoding.UTF8,
IsBodyHtml = true,
Body = cuerpoMensaje,
BodyEncoding = Encoding.UTF8,
Priority = MailPriority.Normal,
})
{
// SMTP Cliente
SmtpClient smtp = new SmtpClient
{
Host = hostSMTP,
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(mailFrom, passwordFrom),
DeliveryMethod = SmtpDeliveryMethod.Network,
Timeout = 2 * 60 * 1000 //2 minutos
};
message.Headers.Add("Disposition-Notification-To", mailFrom);
message.Headers.Add("Return-Receipt-To", mailFrom);
// Send the E-Mail
smtp.Send(message);
}
Thank you very much, I look forward to your response.
Trying to send an email via MVC 5 C#. This newly created email address is on an office 365 server. Tried numerous solutions online but to no avail I get the following error message: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [LO3P265CA0018.GBRP265.PROD.OUTLOOK.COM]'. My code is as follows:
public void ConcernConfirmEmail(Appointments a, EmailConfig ec)
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
tokens.Add("Name", a.sirenDetail.FirstName);
tokens.Add("Time", a.start.ToString("HH:mm"));
tokens.Add("Date", a.start.ToString("dd/MM/yyyy"));
tokens.Add("Location", a.site.SiteDescription);
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(ec.EmailUser, ec.EmailPassword),
TargetName = "STARTTLS/smtp.office365.com",
EnableSsl = true
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("emailadress#myorg.net"),
Subject = "Subject",
Sender = new MailAddress("emailadress214#myorg.net", "password"),
Body = PopulateTemplate(tokens, GetTemplate("ConfirmTemplate.html")),
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
message.To.Add(a.sirenDetail.EmailAddress.ToString());
client.Send(message);
}
}
According to oficcial microsoft documentation, SmtpClass is obsolete for a while now, microsoft encourages deveopers to use new open souce Smtp implementations, like MailKit.
When using MailKit with username and password authentication, you have to set the authentication mechanism to use NTLM.
Here is a working example:
public async Task Send(string emailTo, string subject, MimeMessage mimeMessage, MessagePriority messagePriority = MessagePriority.Urgent)
{
MimeMessage mailMessage = mimeMessage;
mailMessage.Subject = subject;
mailMessage.Priority = messagePriority;
if (emailTo.Contains(';'))
{
foreach (var address in emailTo.Split(';'))
{
mailMessage.To.Add(new MailboxAddress("", address));
}
}
else
{
mailMessage.To.Add(new MailboxAddress("", emailTo));
}
mailMessage.From.Add(new MailboxAddress("Sender", _smtpCredentials.SenderAddress));
using var smtpClient = new SmtpClient
{
SslProtocols = SslProtocols.Tls,
CheckCertificateRevocation = false,
ServerCertificateValidationCallback = (s, c, h, e) => true,
};
await smtpClient.ConnectAsync(_smtpCredentials.Server, _smtpCredentials.Port, SecureSocketOptions.StartTlsWhenAvailable);
await smtpClient.AuthenticateAsync(new SaslMechanismNtlm(new NetworkCredential(_smtpCredentials.User, _smtpCredentials.Password)));
try
{
await smtpClient.SendAsync(mailMessage);
}
catch (Exception ex)
{
}
finally
{
if (smtpClient.IsConnected) await smtpClient.DisconnectAsync(true);
}
}
The most important line here is
await smtpClient.AuthenticateAsync(new SaslMechanismNtlm(new NetworkCredential(_smtpCredentials.User, _smtpCredentials.Password)));
That is setting the NTLM as the authentication mechanism for the client to use.
But
If you are unable to change Smtp library right now, you can try change your code to look like this, as imcurrent using in older services and work fine:
using (var smtpClient = new SmtpClient(smtpServer)
{
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(user, password),
EnableSsl = false,
Port = 587
})
See that the change is on just on the EnableSsl set to false, and not needded to set the TargetName property.
Hope this helps
I'm trying to send an automated email from my desktop application using Visual Studio C# and SMTP. It works when directly connected to the Wi-Fi but the moment I connect to the VLAN that we set up, the SmtpClient.Send() times out.
public static void SendEmail(string toAddress, string subject, string body)
{
string senderID = "email";
const string senderPassword = "password";
try
{
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
Timeout = 30000,
};
if (IsValidEmail(toAddress))
{
MailMessage message = new MailMessage(senderID, toAddress, subject, body);
smtp.Send(message);
}
else throw new Exception();
}
catch (Exception)
{
throw;
}
}
We're using static IP, so I thought maybe it had something to do with DNS since the SMTP host isn't a specific IP.
I am trying to send an email by gmail but this code isn't working, gives connection time out error. If I make the port '587' it gives this error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
string email = // email
string password = // password
string smtp = // smtp.gmail.com
int port = // 465
var from = new MailAddress(email, "");
var to = new MailAddress(message.Destination);
var client = new SmtpClient()
{
Host = smtp,
Port = port,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(email, password)
};
var mail = new MailMessage(from, to)
{
Subject = subject,
Body = body,
IsBodyHtml = true
};
return client.SendMail(mail);
}
I have used very similar code to yours in the past and it worked, but the port number I used was 587.
This is my code:
SmtpClient client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("gmail_login", "gmail_password")
};
using( var message = new MailMessage("your_emailAddress", "destination_Email")
{
Subject ="subject",
Body = "body"
})
client.Send(message);
If you are logging from a new destination/timezone you should first log in through the web browser and confirm that it is you :)
I recently posted another answer that addresses this situation:
You need to make sure that the email account that you're using allows
access from less secure apps.
Simply change a security setting from your account.
Try it here
I am trying to send email using following method. credentials are not given here for security. But they are correct.
static void Main(string[] args)
{
string mailTo = "testmail#testmail.com";
MailMessage mail = new MailMessage("email#email.onmicrosoft.com", mailTo);
mail.Subject = "Test";
mail.Body = "Blank Email";
mail.Priority = MailPriority.High;
mail.IsBodyHtml = true;
// Set the StmpServer name.
SmtpClient mailSmtp = new SmtpClient("Smtp.mail.microsoftonline.com");
// Smtp configuration
mailSmtp.Credentials = new System.Net.NetworkCredential("email#email.onmicrosoft.com", "********");
mailSmtp.Port = 587;
mailSmtp.Timeout = 30000;
try
{
mailSmtp.Send(mail);
}
catch(Exception ex) {
Console.WriteLine(ex.Message.ToString());
}
}
but this is not working. "Failur sending mail" is the message of SmtpException which caught.
i have tried using mailSmtp.UseDefaultCredentials = false; before setting credentials. EnableSsl to true, Deliverymethod to Network. But nothing changed the situation.
Make sure your ISP allows outgoing connections at port 25. If port 25 is closed, you will have this error.