C# send email using implicit ssl - c#

Is there any library preferable free that can be used in order to sens email using implicit ssl protocol. My hosting provider support ssl emails ... but standard .net email client cannot handle that.

Use the TLS port (ie 587) rather than the SSL port. I had the same issue for months until I found this solution.
Sending email in .NET through Gmail

System.Net.Mail does support "explicit SSL" (also known as "StartTLS" - usually on port 25 or 587), but not "implicit SSL" (aka "SMTPS" - usually on port 465).
As far as I know, explicit SSL starts from an unsecured connection, then the STARTTLS command is given and finally a SSL secured connection is made.
Implicit SSL, on the other side, requires that the SSL connection is set up before the two parties start talking.
Some servers (like gmail) accept both, so you simply need to set EnableSsl to true and send to the right port. If your server does not support explict SSL, though, this "simple way" is not an option.
I'm also still looking around for a general solution for using System.Net.Mail with implicit SSL, with no luck so far.
Anyway take a look at this article, it may give you some insight.
[edit: #Nikita is right, fixed port numbers to avoid confusion]

You may still be able to use the deprecated System.Web.Mail.MailMessage API (and set its "http://schemas.microsoft.com/cdo/configuration/smtpusessl" option, for explicit SSL/TLS):
System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage();
// ...
mailMsg.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
true);
Alternatively, if you can, you could run something like stunnel locally to establish an SSL/TLS tunnel from your localhost to your SMTP server. Then, you would have to connect normally (without SSL/TLS) to the tunnel's localhost end as your SMTP server.

Try to check AIM (Aegis Implicit Mail) on https://sourceforge.net/p/netimplicitssl/wiki/Home/

As one of options, our SecureBlackbox includes SMTP component which works via both implicit and explicit SSL and supports different authentication mechanisms (including SASL, NTLM etc).

AspNetEmail supports Explicit SSL and Implicit ssl
http://www.advancedintellect.com/download.aspx

You can use AIM (Aegis Implicit Mail) to send email through implicit SSL:
First install the package: Install-Package AIM
Then Use the sample code to send email
class Mail
{
private static string mailAddress = "{you email address}";
private static string host = "{your host server}";
private static string userName = "{your user name}";
private static string password = "{your password}";
private static string userTo = "{to address}";
private static void SendEmail(string subject, string message)
{
//Generate Message
var mailMessage = new MimeMailMessage();
mailMessage.From = new MimeMailAddress(mailAddress);
mailMessage.To.Add(userTo);
mailMessage.Subject = subject;
mailMessage.Body = message;
//Create Smtp Client
var mailer = new MimeMailer(host, 465);
mailer.User = userName;
mailer.Password = password;
mailer.SslType = SslMode.Ssl;
mailer.AuthenticationMode = AuthenticationType.Base64;
//Set a delegate function for call back
mailer.SendCompleted += compEvent;
mailer.SendMailAsync(mailMessage);
}
//Call back function
private static void compEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
Console.Out.WriteLine(e.UserState.ToString());
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
Console.Out.WriteLine("Error : " + e.Error.Message);
}
}

Related

Mailkit SMTP - StartTLS & TLS flags

I am trying to connect to iCloud via SmtpClient
The settings I am using are as follows:
Server name: smtp.mail.me.com
SSL Required: Yes
If you see an error message when using SSL, try using TLS or STARTTLS instead.
Port: 587
SMTP Authentication Required: Yes - with relevant username and password
If I use SSL I get "Handshake failed due to unexpected packet format"
If I don't use SSL visual studio debugger hangs on connect.
I think the problem is I am not telling the SmtpClient to use tls but I cant find documentation on how to do this.
The code is as follows:
using (var client = new SmtpClient()) {
client.Timeout = 1000 * 20;
//client.Capabilities.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Connect("SMTP.mail.me.com", 587, false); //dies here
//client.Connect(servername, port, useSsl);
//can I set tls or starttls here??
client.Authenticate(username, password);
client.Send(FormatOptions.Default, message);
}
Am I able to set TLS or StartTLS manually. One thing I did try is the following but it did not seem to work
client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true"));
Thanks for any help with this.
The Connect() method that you are using only allows enabling/disabling SSL-wrapped connections which is not the same thing as StartTLS.
Due to the confusion, I've implemented a separate Connect() method that makes this more obvious what is going on:
using (var client = new SmtpClient()) {
// Note: don't set a timeout unless you REALLY know what you are doing.
//client.Timeout = 1000 * 20;
client.Connect ("smtp.mail.me.com", 587, SecureSocketOptions.StartTls);
client.Authenticate (username, password);
client.Send (message);
}
Try that.
You can set your options to "SecureSocketOptions.Auto"
something like this
await client.ConnectAsync(mailService.Host, mailService.Port, SecureSocketOptions.Auto);
MailKit will automatically decide to use SSL or TLS.
According to MailKit Doc
Connect(string host,int port,bool useSsl,CancellationToken cancellationToken = null)
The useSsl argument only controls whether or not the client makes an SSL-wrapped connection. In other words, even if the useSsl parameter is false, SSL/TLS may still be used if the mail server supports the STARTTLS extension.
This worked for me over the SecureSocketOptions.Auto option mentioned previously:
client.Connect(host, port, SecureSocketOptions.None);

Can't send email using implicit SSL smtp server

I wrote up a sample program by copying the code in this KB article with some little edit as far as user's info. It uses the deprecate .NET library System.Web.Mail to do it because the new System.Net.Mail does not support implicit SSL. I went and tested it with Google smtp server on port 465 which is their implicit email port and everything works. However, when I gave this to a client to test it at his network, nothing get sent/receive, here is the error:
2013-03-07 15:33:43 - The transport failed to connect to the server.
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.Send(MailMessage message)
I'm not very well versed when it comes to email SSL so here is my possible theory to the root cause:
Assume he is using the right smtp server and right port (SSL port), I wonder if if any of the following could be the cause:
They are using SSL on the mail server and yet he does not have the certificate installed on the machine where he runs my program from even though he is on the same domain and use the same email domain as a sender.
They are using SSL but they maybe using NTLM or Anonymous authentication while my program uses basic authentication.
Sorry if I provide little information because I myself is quite foreign in this area so I'm still researching more.
Do you know of any steps I can do at my end to ensure my little test program can send using the smtp server of an implicit SSL email server?
Edit: I did add the following line in my code to indicates I'm using SSL.
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
Maybe this is to late to answer but have a look on https://sourceforge.net/p/netimplicitssl/wiki/Home/
You can send mail to port 465
Without the need of modifying your code, that much.
From the wiki page of project :
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("you#gmail.com", "your name");
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MimeMailAddress("yourfriend#gmail.com", "your friendd's name"));
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.EnableSsl = true;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.PlainText;
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
//Send email
emailer.SendMessageAsync();
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
Console.Out.WriteLine(asynccompletedeventargs.UserState.ToString());
}
Here I am using gmail smtp to send mail using c#. See the code below. It will give you an insight, How the stuffs are working. Replace gmail settings with your email server settings. Dont worry about the security certificates, they will be taken care of by the framework itself.
public static bool SendMail(string to, string subject, string body)
{
bool result;
try
{
var mailMessage = new MailMessage
{
From = new MailAddress("your email address")
};
mailMessage.To.Add(new MailAddress(to));
mailMessage.IsBodyHtml = true;
mailMessage.Subject = subject;
mailMessage.Body = body;
var userName = "your gmail username";
var password = "your gmail password here";
var smtpClient = new SmtpClient
{
Credentials = new NetworkCredential(userName, password),
Host = smtp.gmail.com,
Port = 587,
EnableSsl = true
};
smtpClient.Send(mailMessage);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
The piece of code you were referencing was pretty old and obselete too. CDO was used in ASP apps to send mails. I think you havent scroll down to see
Article ID: 555287 - Last Review: April 7, 2005 - Revision: 1.0
APPLIES TO
Microsoft .NET Framework 1.1
You are refering a code that is pretty old... anyways follow the code shown up, everything will be FINE...
UPDATE
My bad, I have'nt read it carefully. But
I am leaving the above code as it is, as it might be a help for you
or any other guy, who need the mailing functionality via SSL over
gmail or any other server later.
. Then in such case you need some third party app.I found you a library See here

Sending email using Smtp.mail.microsoftonline.com

The context:
We’re a small company that does not have an Exchange Server (or anyone dedicated to it) yet we still need to have/send emails.
We’ve decided to use Microsoft Online Services (MOS)
The Objective:
We have a web server (Windows Server 2003 R2 with IIS 6.0) and have deployed a C# ASP.Net MCV application.
The web application needs to send emails each time a user creates an account.
According to the documentation we need to use port (587) and make sure Transport Layer Security (TLS) enable. In addition, the FROM address being used must be of type “Authoritative” which it is when I double check via the Microsoft Online Administration Center
The code:
The C# code I have should be trivial and is the following:
SmtpClient server = new SmtpClient("Smtp.mail.microsoftonline.com");
server.Port = 587;
server.EnableSsl = true;
server.Credentials = new System.Net.NetworkCredential("xxx#domain.com", "123abc");
server.UseDefaultCredentials = false;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("xxx#domain.com");
mail.To.Add("johndoe#domain.com");
mail.Subject = "test subject";
mail.Body = "this is my message body";
mail.IsBodyHtml = true;
try
{
server.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
The error:
I’ve created a simple winform application with the above code to test the sending of emails…
I’ve tested the winform application locally on my computer (Windows XP) and on the Server.
In both attempt, I keep receiving the following error message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
After Googling for a while I still haven’t found the reason why…In addition, most of the answers I’ve found are making a reference to the Exchange Management Console which we don’t seem to have (or installed) hence why we are using Microsoft Online Services…
Questions:
1) As a paying customer of MOS, my initial understanding is that I shouldn’t have to install (or have) an Exchange Management Console on our server…in fact, this should be completely irrelevant in order to achieve my task.
2) I’ve also tried enabling TLS inside our IIS 6.0 but to no avail…
3) We are grasping at straws here because what we seem to do looks like something amazingly trivial…
4) Should we simply abandon the idea of using MOS’s SMTP server and use another one? Such as Gmail’s ? If so…then why bother paying a monthly fee for MOS?
If any one has any help/advice that can help me shed some light on this, that would be great!
Sincerely
Vince
WOW…I believe we’ve found the culprit!!!
By commenting this line of code:
//server.UseDefaultCredentials = false;
Everything started to work!
I’m now able to send emails inside and outside our domain…
What puzzles me the most is that, according to the documentation, the default value of this UseDefaultCredentials property is set to false
So…when I manually set it to false it doesn’t work but when I comment the line (which also set’s it to false because of its default value) it works!
If this is a known issue or if anyone has an answer for that, I’d be curious to know!
looking in Reflector on UseDefaultCredentials property, you can see that it also changes the trasnport.Credentials value, so when you called this property with a false value, it changed the transport credentials to null.
the problem is that you called this property after setting the credentials in the line before that,
it nullified the credentials.
so bottom line, you shouldn't set the credentials and call this property afterwise.
you can try this sample
private void Button1_Click(System.Object sender, System.EventArgs e)
{
try
{
MailMessage myMessage = new MailMessage();
SmtpClient myClient = new SmtpClient("yourserver");
myClient.Port = "587";
myClient.Host = "your server";
myClient.UseDefaultCredentials = false;
myClient.Credentials = new System.Net.NetworkCredential("username", "password");
myMessage.From = new MailAddress("sender");
myMessage.To.Add("recipient");
myMessage.Subject = "Subject email";
myMessage.Body = "body email";
myClient.EnableSsl = true;
myClient.Send(myMessage);
}
catch (Exepiton ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Bye
5.7.1 is not an authentication issue, but a relay issue. In order to prevent anyone from using your server (or account, as the case may be) the smtp server is configured to only allow mail to users outside your domain if it is comming from an authoritive address. Verify that the address you have listed here
mail.From = new MailAddress("xxx#domain.com");
is the same as the one you are authenticating as. Also, make sure that the domain of the address listed is in the authoritive domains list.
What worked for me was what the-dude suggested Send SMTP email using System.Net.Mail via Exchange Online (Office 365) , on changing the email "from" address to be the same as the login for the stmp address
AND
doing what Vince suggested at the end Sending email using Smtp.mail.microsoftonline.com for commenting out "smtpClient.UseDefaultCredentials = false;"
Be sure to double check that your username is correct. It is not necessarily the same as your from email address. For example the from address may be "no-reply#yourdomain.com" but the username could be "mail-svc#yourdomain.onmicrosoft.com" depending no your setup and integration with Azure Active Directory etc.

C# SMTP virtual server doesn't send mail

C# SMTP virtual server doesn't send mail. Here's the code:
public static void SendEmail(string _FromEmail, string _ToEmail, string _Subject, string _EmailBody)
{
// setup email header .
SmtpMail.SmtpServer = "127.0.0.1";
MailMessage _MailMessage = new MailMessage();
_MailMessage.From = _FromEmail;
_MailMessage.To = _ToEmail;
_MailMessage.Subject = _Subject;
_MailMessage.Body = _EmailBody;
try
{
SmtpMail.Send(_MailMessage);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
String str = ex.InnerException.ToString();
}
}
It is an Interop exception because that .NET code is relying on Interop(erability) services, non-managed stuff. The message however is pretty clear, the server is unable to relay because it has been configured to reject relaying of emails.
Many years ago that was not a problem and you could virtually use any public SMTP server to send emails. With the advent of SPAM the whole game changed, now in most servers relaying is disabled and your mail send request is rejected.
What you will need here so that it does not reject your mail, is to authenticate your request (account/user and password on that server). It has to be a valid username & password combination known to that SMTP server. You do that by setting those (out of my head sorry) in the .Credentials property. See also the UseDefaultCredentials property, if you set Credentials you need to make sure UseDefaultCredentials is false.
If the error is this:
550 5.7.1 Unable to relay for ragaei.mahmoud#invensys.com
Then your SMTP server cannot send to that email address. Use a different SMTP server or configure it to relay out to the internet. The local one will probably only send to addresses on your own domain. If this is an SMTP server configuration question, you may have more luck asking on Superuser.

C# SMTP email sending code fails for Yahoo Mail but works fine for other servers, can anyone help?

I am using this code to send an SMTP email via the yahoo SMTP server, it is for a personal project I am writing.
using System.Net.Mail;
using System.Net;
SmtpClient theClient = new SmtpClient("smtp.mail.yahoo.com", 465);
theClient.UseDefaultCredentials = false;
theClient.Credentials = new NetworkCredential("username", "password");
theClient.EnableSsl = true;
MailMessage theMessage = new MailMessage("username#yahoo.com",
"to.someone#gmail.com");
theMessage.Subject = "Dave test from C# subject";
theMessage.Body = "Dave test from C# body";
theClient.Send(theMessage);
It's all pretty standard code for sending SMTP email, but... the server seems to throw an error. It forcibly terminates the connection. This does not happen if I use other SMTP servers like Gmail, Windows Live or various other ISP Smtp servers.
This is the exception and stack trace:
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ConsoleApplication1.Program.Main(String[] args) in E:\dev\ARCSoftware.FTPProcessor\ConsoleApplication1\Program.cs:line 28
I know the problem is not environmental though as I can send to the same server with these exact settings using Outlook Express. I am wondering if I need to send a certificate or something?
If you, or anyone you know where has any ideas about this I would greatly appreciate some help.
using System.Net.Mail;
using System.Net;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_Send_Click(object sender, RoutedEventArgs e)
{
MailMessage oMail = new MailMessage(new MailAddress("username#yahoo.com"), new MailAddress("username#yahoo.com"));
SmtpClient oSmtp = new SmtpClient();
oSmtp.Host = "smtp.mail.yahoo.com";
oSmtp.Credentials = new NetworkCredential("username", "password");
oSmtp.EnableSsl = false;
oSmtp.Port = 587;
oSmtp.Send(oMail);
}
}
It's not supported through 465, but the following post details a workaround
How can I send emails through SSL SMTP with the .NET Framework?
UPDATE: This link details why it might work through Outlook Express, but not through the System.Net.Mail
http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx
Port 465 isn't supported by System.Net.Mail.SmtpClient.
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.enablessl.aspx
From the Remarks Section:
This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.
Edit:
You could try using port 587 instead (if Yahoo supports it).
I had the same problem until I set the port to 587 and disabled SSL.
I think you should revert to using System.Web.Mail which lets you control fields that are not accessible through the newer System.Net.
Try to play with those. For instance you could try this:
(use is documented here, fields are documented here)
MailMessage msg = new MailMessage();
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.mail.yahoo.com");
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
// try "2", I have not tested for yahoo mail
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "1");
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); // 0= anonymous - 1=basic - 2=NTLM
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "yahoousername");
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "yahoopwd");

Categories