Sending authenticated mail using SmtpClient - c#

I want to send an email using c# SmtpClient via an smtp host that requires authentication or it will fail with relay denied. I have read many posts, but none quite solve my issue which is that while I specify NetworkCredentials, in the communication with the mailhost, no credentials are passed along. This confuses me.
This is the code that sets the credential and sends the mail:
using (SmtpClient smtp = new SmtpClient
{
Host = smtpserver,
Port = port,
EnableSsl = ssl
})
{
if (username.Length > 0)
{
Console.WriteLine("Setting credentials to\nusername: {0}\npassword: {1}", username, password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(username, password);
}
smtp.Send(message);
}
The correct credentials are printed to the console.
This is the TCP stream as captured by Wireshark:
220 mail.myhost.com Microsoft ESMTP MAIL Service ready at Tue, 20 Jan 2015 12:44:19 +0100
EHLO DK-XYZ-800SFF1
250-mail.myhost.com Hello [172.16.123.132]
250-SIZE 52428800
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-AUTH
250-8BITMIME
250-BINARYMIME
250 CHUNKING
MAIL FROM:<myemail#myhost.dk>
250 2.1.0 Sender OK
RCPT TO:<someemail#gmail.com>
550 5.7.1 Unable to relay
Clearly no authentication attempts are being made, despite the credentials having been set on SmtpClient.

I solved the issue and learned a bit in the process. While my code was correct, one of the parameters that I did not provide was the port information. From the SMTP log above, we can see the AUTH line is empty, i.e. has no protocols available for authentication. That is why SmtpClient didn't send any credentials.
The reason why AUTH line didn't have any methods for authentication was because I was using port 25 for communication. As soon as I switched to port 587, smtp reported that authentication was possible and credentials were sent and mails were sent as intended.

public static void CreateTestMessage2(string server)
{
string to = "jane#contoso.com";
string from = "ben#contoso.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString() );
}
}`

Related

Getting MailKit.Security.SslHandshakeException on my .NET 5.0 web API when trying send an email through Gmail SMTP

I'm trying to setup email alerts from my .NET core web api. I've created the following email service to test it.
I'm connecting to the gmail smtp server using the following details:
url:smtp.gmail.com
port: 465
ssl: true
And authenticating using my gmail address and password.
using MailKit.Net.Smtp;
using MimeKit;
public class EmailService
{
public SmtpClient ConnectSMTP() {
SmtpClient client = new SmtpClient();
//remove hard coding from this and place details in env settings
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("<EMAIL>", "<PASSWORD>");
return client;
}
public void EmailTest(string toAddress)
{
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress("EzGig","ezgigrota#gmail.com");
msg.From.Add(from);
MailboxAddress to = new MailboxAddress("EzGig User", toAddress);
msg.Subject ="Test Email";
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = "This is a test email body";
msg.Body = bodyBuilder.ToMessageBody();
SmtpClient client = ConnectSMTP();
client.Send(msg);
client.Disconnect(true);
client.Dispose();
}
}
When I try to call the EmailTest method from one of my controllers I'm getting the following error
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.
The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
I had the same issue. #jstedfast was correct but he forgot to mention one thing.
Ensure the client.CheckCertificateRevocation = false; comes before client.connect()
client.CheckCertificateRevocation = false;
client.connect();
Based on the error message, it probably means that the CRL server was down which would prevent the SslStream from checking revocation status of the server's SSL certificate.
You can disable CRL checks by setting client.CheckCertificateRevocation = false;

Send email from C# does not work

I am trying to send an email with C# code, copied from examples on MSDN (e.g. https://msdn.microsoft.com/en-us/library/14k9fb7t%28v=vs.110%29.aspx)
// from and password contain my credentials
// to contains a valid email address
public static void CodeExample()
{
try
{
using (MailMessage mail = new MailMessage(from, to))
{
using (SmtpClient server = new SmtpClient("smtp.googlemail.com"))
{
mail.From = new MailAddress(from);
mail.To.Add(new MailAddress(to));
mail.Subject = "Test subject";
mail.Body = "Test message";
mail.IsBodyHtml = false;
server.Port = 465;
server.Credentials = new System.Net.NetworkCredential(from, password);
server.UseDefaultCredentials = true;
server.EnableSsl = true;
server.ServicePoint.MaxIdleTime = 1;
server.Timeout = 60000;
Console.WriteLine("Sending to {0} by using SMTP host {1} port {2}.", to.ToString(), server.Host, server.Port);
server.Send(mail);
Console.WriteLine("mail Sent");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Inner Exception:");
Console.WriteLine(ex.InnerException?.ToString());
}
}
But I always get an exception:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException:
Unable to read data from the transport connection: net_io_connectionclosed.
The ‘from’ address details have been checked and seem OK. Sending from a Yahoo! account fails in the same way. I have tried lots of different combinations of SmtpClient properties. There are no messages in my firewall log.
Using Thunderbird, I can send from both the Googlemail and Yahoo! accounts without problems.
I would be grateful for any hints on how to get this to work.
Edit
I have seen this post SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
Google mail fails on port 587 (both using and commenting-out UseDefaultCredentials = true and EnableSsl = true), reporting that I have an insecure app. I will try Yahoo! on port 587 later.
Thanks for the help. Using port 587 was important, as shown at SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
I still cannot get smtp.googlemail.com or smtp.gmail.com to work, but that is covered at SmtpClient with Gmail.
My program is now working with smtp.mail.yahoo.com.

Trying to use smpclient() for sending mail to the user from my host

its my first time to work smpclient() function in C# .
I'm trying to send one simple mail to my E-mail address from my host webmail .
my details :
My website : www.chicardari.ir
Source mail : info#chicardari.ir (from)
Destination email : vbhost.ir#gmail.com (to)
title : title_Hello world body : body_Hello world
my code.
protected void BtnRegister_Click(object sender, EventArgs e)
{
SmtpClient smtpClient = new SmtpClient("mail.chicardari.ir", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#chicardari.ir", "Passwprd");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info#chicardari.ir", "chikardari");
mail.To.Add(new MailAddress("vbhost.ir#gmail.com"));
mail.CC.Add(new MailAddress("vbhost.ir#gmail.com"));
smtpClient.Send(mail);
}
I used:
using System.Net.Mail;
using System.Net;
after executing i face to this error :
System.Net.WebException: The remote name could not be resolved: 'mail.chicardari.ir'
note : i dont know what is my host port and even how to get it .
please help me emphasized text
Got it mate.
By using this tool I can see it is connecting
http://www.adminkit.net/smtp.aspx
Connecting to mail server.
Connected.
220 WIN-T2D6ANG73NS.sabasystems.ir ESMTP MailEnable Service, Version: 8.04-- ready at 09/09/14 16:04:27
EHLO Server01
250-sabasystems.ir [64.85.165.1], this server offers 4 extensions
250-AUTH LOGIN
250-SIZE 5120000
250-HELP
250 AUTH=LOGIN
RSET
250 Requested mail action okay, completed
MAIL FROM:
250 Requested mail action okay, completed
RCPT TO:
503 This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.
SMTP protocol error. 503 This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server..Forcing disconnection from SMTP server.
QUIT
221 Service closing transmission channel
Disconnected.
SMTP session Takes 1.9500034 Seconds
if you replace your host from mail.chicardari.ir to chicardari.ir it will work.
protected void BtnRegister_Click(object sender, EventArgs e)
{
SmtpClient smtpClient = new SmtpClient("chicardari.ir", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#chicardari.ir", "Passwprd");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info#chicardari.ir", "chikardari");
mail.To.Add(new MailAddress("vbhost.ir#gmail.com"));
mail.CC.Add(new MailAddress("vbhost.ir#gmail.com"));
smtpClient.Send(mail);
}
If still it does not work then speak to your service provider.
Best of luck!

Send mail works locally but not on server?

This code works locally, but when I upload it to my server on Godaddy, it does not send the e-mail. Any idea why it doesn't work on their server? What do I need to change?
try {
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("Myemail#gmail.com");
mail.To.Add("Myemail#gmail.com");
mail.Subject = "New sign up";
mail.Body = "New member";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("Myemail#gmail.com", "**Mypass**");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
} catch(Exception ex) {
throw ex;
}
They may be blocking outgoing SMTP connections in order to prevent spammers from using their service to send spam. You should check what error messages you're getting and check your server host's policy.
There are a couple of things you need to do when sending from inside a site hosted from Godaddy. Use their relay server to send the message (this won't work from your dev machine, you'll have to test it live after you upload it). Here is the relay server info. Also make sure the "from" address is an email within the same domain. I usually use the same as the toAddress. See here for info on why this is necessary.
This is the code I'm using to send from a site inside Godaddy:
btnSend.Disabled = true;
const string serverHost = "relay-hosting.secureserver.net";
var msg = new MailMessage(toAddress, toAddress);
msg.ReplyTo = new MailAddress(emailFrom);
msg.Subject = subject;
msg.Body = emailBody;
msg.IsBodyHtml = false;
try
{
var smtp = new SmtpClient();
smtp.Host = serverHost;
smtp.Credentials = new System.Net.NetworkCredential("account", "password");
smtp.Send(msg);
}
catch (Exception e)
{
//Log the errors so that we can see them somewhere
}
You need to send your email via the godaddy smtp servers. I experienced the same issue with them before I think. I believe they give instructions of how to login via their FAQ.
If you have ssh access to the server, try to telnet smtp.google.com via 25 and 465 ports also. If you get a timeout, then you're likely firewalled from connecting to these ports outside a certain IP range.
Port 587 is for TLS. As you're using SSL, try port 465.

Send mail from C# code using lotuslive credentials?

I am trying to send mail from C# code using lotuslive smtp. But I have no success in sending the mail. everytime it says {"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."}.
My code is working fine for other email hosts like gmail and yahoo.
below is the code that I have used.
MailMessage message = new MailMessage();
message.From = new MailAddress("fromaddress");
message.To.Add(new MailAddress("toaddress"));
message.Subject = "Test";
message.Body = "test";
SmtpClient client = new SmtpClient("companyname-com-smtp.mail.lotuslive.com", 465);
client.UseDefaultCredentials = false;
NetworkCredential credential = new NetworkCredential("companycredentials", "password");
client.Credentials = credential;
client.EnableSsl = true;
try
{
client.Send(message);
}
catch(Exception ex)
{
}
Outgoing SSL SMTP Server: -smtp.mail.lotuslive.com (port: 465) Please
Note: Outgoing SMTP access for third party email clients is not
available for Trial accounts.
If it is trail account then may cause some problems.
MailClient = new SmtpClient();
MailClient.Host = "smtp.mail.lotuslive.com/your host address";
MailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
MailClient.Credentials = new System.Net.NetworkCredential(username, password);
MailClient.EnableSsl = true;
MailClient.Port = 465;
If you do not have demo account then Check this link - How to configure client in Outlook 2003.
Check these outlook configure settings match to your code settings.
If all this stuff is not the issue then it may be problem at your mail server. Check these links for information:
An existing connection was forcibly closed by the remote host in SMTP client
System.Net.Mail with SSL to authenticate against port 465

Categories

Resources