I am trying to send an email to MailTrap.io its a free smtp portal for checking the email but im getting the following error.
I am using MailKit to send the email
https://mailtrap.io
public async Task SendEmailAsync(string email, string subject, string message)
{
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("David", "davidnoreply#gmail.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("HTML") { Text = message };
using (var client = new SmtpClient())
{
client.LocalDomain = "http://localhost:52101";
await client.ConnectAsync("smtp.mailtrap.io", 584, true);
client.Authenticate("16729fdfa173b4", "0e6de61c67b069");
client.Send(emailMessage);
//await client.emailMessage(emailMessage).ConfigureAwait(false);
//await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}
}
But the following error presents itself I have tried on port 25 but then i get an error about ssl.
No connection could be made because the target machine actively
refused it. 127.0.0.1:25
If I change it to port 25 I get the following.
An error occurred while attempting to establish an SSL or TLS connection.
This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
Another possibility is that you are trying to connect to a port which does not support SSL/TLS.
It is also possible that the set of SSL/TLS protocols supported by the client and server do not match.
See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.
Edit 2
I removed the ssl but stil the same error above.
public async Task SendEmailAsync(string email, string subject, string message)
{
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("David", "david#gmail.com"));
emailMessage.To.Add(new MailboxAddress("", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("HTML") { Text = message };
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.mailtrap.io", 25, true);
client.Authenticate("16729fdfa173b4", "0e6de61c67b069");
client.Send(emailMessage);
//await client.emailMessage(emailMessage).ConfigureAwait(false);
//await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
catch (Exception ex)
{
// TODO: handle exception
throw new InvalidOperationException(ex.Message);
}
}
Related
Am not sure whether the old method of sending Mail using Mailkit is quite working with this code below
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_emailConfig.SenderName, _emailConfig.SenderAddress));
emailMessage.To.Add(new MailboxAddress(email));
emailMessage.Subject = subject;
var builder = new BodyBuilder
{
HtmlBody = message
};
emailMessage.Body = builder.ToMessageBody();
using var smtp = new SmtpClient
{
ServerCertificateValidationCallback = (s, c, h, e) => true
};
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), false).ConfigureAwait(false);
await smtp.AuthenticateAsync(_emailConfig.Username, _emailConfig.Password).ConfigureAwait(false);
await smtp.SendAsync(emailMessage).ConfigureAwait(false);
await smtp.DisconnectAsync(true).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
but am having exceptions if i use the code above to send email
nvalidOperationException: 534: 5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv
5.7.14 26mzQKtlwfyEdGzHHdpi3ewWG6skAWgOBbdNNYmwzr9Sg3fGu-KixLAfODpJsVafutidE
5.7.14 8xBOp_8rNCvk9Y6iEcOkDlcZ1d-483zQ1Krw04NvqxQdq3w4iTtC8E9bL8uGprgV>
5.7.14 Please log in via your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/answer/78754 o5sm2555896wmh.8 - gsmtp
so when i changed this line of code below to use SSLS, A new error came out
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), true).ConfigureAwait(false);
Exception returned
InvalidOperationException: An error occurred while attempting to establish an SSL or TLS connection.
This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
Another possibility is that you are trying to connect to a port which does not support SSL/TLS.
It is also possible that the set of SSL/TLS protocols supported by the client and server do not match.
See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.
have searched everywhere on how to do it,even turned on my less secured app. some recommended sendGrid, i created a free account with them also,but i dont have access to the account created. Does anyone knows how to fix the code above using Mailkit
Try it like this.
using (var smtpClient = new SmtpClient())
{
smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
await smtpClient.ConnectAsync("host", port, false);
if (smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
{
smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
await smtpClient.AuthenticateAsync(username, password);
}
await smtpClient.SendAsync(mailMsg);
smtpClient.Disconnect(true);
}
I'm working in ASP.Net Core and trying to send email using smtp client from gmail. Have following code but it's not working
Have seen following post as well but it doesn't work
http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/
It thorws following error
System.NotSupportedException: The SMTP server does not support authentication
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("From Name", "fromEmail#gmail.com"));
emailMessage.To.Add(new MailboxAddress("To Name", "toEmail#gmail.com"));
emailMessage.Subject = subject;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = message;
emailMessage.Body = bodyBuilder.ToMessageBody();
var client = new SmtpClient();
try
{
await client.ConnectAsync("smtp.gmail.com", 25, SecureSocketOptions.None).ConfigureAwait(false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync("fromEmail#gmail.com", "fromPassword"); //error occurs here
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
catch(Exception e)
{
}
The NotSupportedException is thrown because GMail does not support authentication without using an SSL/TLS connection because it only supports non-encrypted password-based authentication mechanisms.
I would recommend connecting like this:
client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls)
Hope that helps.
I've been banging my head against this one for weeks, but today was the day I promised I'd get it fixed. So far I've failed.
I am trying to send an email from a hosted MVC application, via a Hosted Exchange server. The IT department has said and confirmed that they have allowed the IP of the MVC application through. However, the following code gives me "An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25" every time.
ActionResult Test()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("valid.email.address");
message.Subject = "Test Email";
message.To.Add(new MailAddress("another.valid.email.address"));
message.Body = "Hey, this is a test!";
using (SmtpClient client = new SmtpClient())
{
client.Credentials = new System.Net.NetworkCredential("username", "password");
client.Port = 25;
client.EnableSsl = true; // Either true or false gives same result
client.Host = "actual.host.url";
try
{
client.Send(message);
}
catch (Exception ex)
{
ViewBag.LogMessage = string.Format("Error: {0}<br />{1}<br />{2}", ex.Message, ex?.InnerException.Message, ex?.InnerException?.InnerException.Message);
return View();
}
ViewBag.LogMessage = string.Format("client.Host: {0}<br />Client.Port: {1}<br />Client.EnableSsl: {2}<br />message.To[0].Address: {3}", client.Host, client.Port, client.EnableSsl ? "true" : "false", message.To[0].Address);
}
return View();
}
The value of the LogMessage is:
Error: Failure sending mail.
Unable to connect to the remote server
An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25
Any suggestions would be welcome! I've tried port 587 with no luck. I've tried with and without credentials, with or without SSL, username matching from address or not. I've run out of things to try.
Thanks!
Try the following code, the first line tells SMTP Client to ignore any issue with the SSL cert if its provide from an invalid provider.
ServicePointManager.ServerCertificateValidationCallback =(sender,certificate, chain, sslPolicyErrors) => true;
var smtpClient = new SmtpClient("oba.exchangeserver.com")
{
Port = 587,
EnableSsl = true,
Credentials =
new NetworkCredential("username","password")
};
return smtpClient;
I got the following exception when trying to send email using System.Net.Mail.SmtpClient:
System.Net.Mail.SmtpException: The SMTP host was not found.
Inner exception:
System.Net.Sockets.SocketException: The requested service provider could not be loaded or initialized
My email sending code is rather simple:
private async Task SendEmail(string to, string subject, string email)
{
MailMessage msg = null;
SmtpClient smtp = null;
try
{
var set = Settings.Default;
msg = new MailMessage(set.EmailFrom, to, subject, email);
smtp = new SmtpClient(set.SMTPServer, set.Port)
{
EnableSsl = true,
Credentials = new NetworkCredential(set.EmailUsername, set.EmailPassword),
Timeout = 20000
};
await smtp.SendMailAsync(msg);
}
catch (Exception e)
{
_log.Error("Error on sending email", e);
throw;
}
finally
{
if (msg != null) msg.Dispose();
if (smtp != null) smtp.Dispose();
}
}
This error does not happen each time, but rather often. I tried to google it but have not found anything useful. The internet connection seems to be stable when I get this error.
Any ideas why this could happen?
Apologies for not posting this as a comment, I don't have sufficient rep.
I run a process using a very similar implementation to that and I have had the same thing happen to me. Try reducing SMTP the timeout, a new connection will be refused if there are too many requests that haven't let go of their existing connection yet. It's helped with my specific implementation.
I am writing a small utility to help process some MySQL tasks every night and have it email my personal email if it fails (this is a personal project, so no company smtp server or anything, emails going through public outlook accounts).
I tested about 5 times and each send was successful, but now any attempts to send email I get this exception:
Error sending test email: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade. OutboundSpamException: WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade.[Hostname=BY2PR0101MB1461.prod.exchangelabs.com]
A bit of an oops on my part - didn't think Outlook would consider it as spam on the 6th try - is there anything I can do in Outlook to correct this?
I am using a service account I created in outlook to send these emails to my personal inbox.
The actual code in question:
class JobMailer
{
private string email_to;
private string email_from;
private string password;
private string email_smtp;
private bool use_ssl;
private int port;
public void Send(string subject, string body)
{
MailMessage mail = new MailMessage(email_from, email_to);
using (SmtpClient client = new SmtpClient
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = use_ssl,
Host = email_smtp,
Timeout = 100000,
Port = port,
Credentials = new NetworkCredential(email_from, password)
})
{
mail.Subject = subject;
mail.Body = body;
client.Send(mail);
}
}
public JobMailer(string emailTo, string smtp, string emailFrom, string pw, int p, bool ssl)
{
email_to = emailTo;
email_from = emailFrom;
password = pw;
email_smtp = smtp;
port = p;
use_ssl = ssl;
}
}
I resolved this by verifying the account I was trying to use. Each time you encounter this error an email is sent to the account with instructions on what you need to do to resolve the error. Typically you will need to verify against a phone number.
Got this error trying to send lots of emails to myself at Outlook.com, using SMTP.
To fix it I simply added a 5 second delay between the sends, for example:
foreach(var mail in mailToSend)
{
await smtpClient.SendMailAsync(mail);
Console.WriteLine("Sent email: " + mail);
await Task.Delay(5000);
}
If you aren't doing this just as a test, then you can contact the Outlook.com team and ask them to whitelist your IP (make sure you have SPF, rDNS, etc. setup first).