How to check if a recipient email address domain has TLS implemented? - c#

We are trying to check if a recipient email id (domain of a given email id) has TLS implemented or not. If not implemented we cannot send the email. Is there any way in C# to check it? e.g. Following is a service where we can enter any email id and it will tell us if that email domain has TLS implemented or not. https://www.checktls.com/TestReceiver How to do this in C#? C# email client comes with the property smtpClient.EnableSsl = true; question is what will happen if at the recipient side the TLS is not implemented? Will it fail or it will go through? If it fails that's what we want. Our SMTP server has TLS implemented.
I tried STARTTLS command and EHLO from telnet. It gives 250 STARTTLS, which tells me that the destination server has TLS implemented. How to do it programmatically?
smtpClient.EnableSsl = true;

If you use a library like MailKit, you can do this:
bool supportsStartTls;
using (var client = new SmtpClient ()) {
client.Connect ("smtp.host.com", 587, SecureSocketOptions.None);
supportsStartTls = client.Capabilities.HasFlag (SmtpCapabilities.StartTls);
client.Disconnect (true);
}
If you want to use MailKit to send mail, you have full control over what happens if STARTTLS is not available.
For example, if you wanted it to fail if STARTTLS is not supported, then use SecureSocketOptions.StartTls as the third argument to the Connect method.
If you want MailKit to use STARTTLS when it is available but not fail if it isn't, then use SecureSocketOptions.StartTlsWhenAvailable instead.

Related

When is it necessary to enable SSL on MailKit

I read on the Microsoft website that the SmtpClient was obsolete and they recommended using the MailKit for it's replacement.
I'm in the process of writing an application to make use of the MailKit.
This is what I have so far:
// *************** SEND EMAIL *******************
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
//accept all SSL certificates
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.IsSslEnabled);
if (emailSettings.IsAuthenticationRequired)
{
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailSettings.SmtpUsername, emailSettings.SmtpPassword);
}
// timeout = 20 seconds
client.Timeout = 20000;
client.Send(message);
client.Disconnect(true);
}
When I set this part:
client.Connect(emailSettings.SmtpServer, emailSettings.SmtpPort, emailSettings.IsSslEnabled);
the last parameter is bool useSSL, which I set to true. My email server is hosted by Rackspace so I know that it uses SSL. When I set this option to true, it fails to send but if I set this option to false, it sends fine.
Shouldn't this line catch the certificate type:
client.ServerCertificateValidationCallback
If so, why wouldn't useSSL on the connect not work? Do I need to set the useSSL to false? I'm confused on how the useSSL works when I have the line above.
Mail protocols (SMTP, IMAP, and POP3) all have 2 different ways of doing SSL.
System.Net.Mail.SmtpClient only implemented support for the STARTTLS way of doing SSL whereas MailKit does both.
When you specify useSsl as true in MailKit's Connect method, it assumes that you meant to use an SSL-wrapped connection (which is different from STARTTLS).
To make this less confusing, MailKit has a Connect method that takes a SecureSocketOptions argument instead of a bool.
The options are as follows:
None: Don't use any form of SSL (or TLS).
Auto: Automatically decides which type of SSL mode to use based on the specified port. Note: This only works reliable when the port is a standard defined port (e.g. 25, 587 or 465 for SMTP).
SslOnConnect: This specifies that MailKit should connect via an SSL-wrapped connection.
StartTls: Use the STARTTLS method for SSL/TLS encryption. If the server doesn't support the STARTTLS command, abort the connection.
StartTlsWhenAvailable: Use the STARTTLS method for SSL/TLS encryption if the server supports it, otherwise continue using an unencrypted channel.
Since you are using SMTP, you might find this useful:
Port 25 was the original port used for SMTP and it originally only supported unencrypted communications.
Later, administrators and users demanded SSL encryption so admins and mail clients started supporting SSL-wrapped connections on port 465 because this was very easy to do for admins (no server software needed to be upgraded and clients that didn't support SSL-wrapped connections could continue connecting on port 25).
After a few years of this, mail protocol authors introduced the STARTTLS command extension for IMAP, SMTP and POP3 (well, for POP3, the command is STLS but it is otherwise the same thing) that clients could optionally use if they supported it. This extension only made sense on the original (non-SSL-wrapped) ports.
These days STARTTLS is the preferred method for encrypting communications between a client and a mail server, but SSL-wrapped ports are still in wide use as well.
MailKit treats port 587 the same as it treats 25. In other words, it treats port 25 and 587 as a plain-text connection port but will switch to SSL/TLS if requested to do so via STARTTLS.

smtp.office365.com subject encoding issues

I try to send emails with my dedicated office365 account but I have issues with subject encoding - all my special characters are replaced with "?".
Code I use is pretty simple and works fine with different test account at smtp-mail.outlook.com.
using (var mailMsg = new MailMessage(sender, recipient))
{
mailMsg.IsBodyHtml = true;
mailMsg.Subject = "Hello world żółćąź";
mailMsg.Body = body;
using (var smtpClient = new SmtpClient())
{
smtpClient.Credentials = new NetworkCredential("email", "password");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.office365.com";
smtpClient.Port = 587;
await smtpClient.SendMailAsync(mailMsg);
}
}
I tried to set all possible subject encoding with no luck. Also converting subject string to Base64String also don't work. Also tried to set Content-Type header charset... All of the resolutions I found didn't help me. Maybe this is some specific SmtpClient issue realated only with office365?
And also setting the body encoding did not help
mailMsg.BodyEncoding = Encoding.UTF8;
I had the same issue with my company's account. Here are my findings so far:
It looks like the Office365 e-mail servers enabled the SMTPUTF8 extension a few months ago which changes the behavior of the System.Net.Mail.SmtpClient class into sending different SMTP commands and a different DATA payload.
In my case the message would always arrive fine when sent to another Office365 account but for other accounts we received e-mail bounce notices from the remote SMTP server which accepted the relayed e-mail message from Office365. The error was something like "Invalid data received, expected 7-bit-safe characters". I could thus imagine that the remote SMTP server from the OP might silently replace all characters outside the low 7-bit range with a question mark.
Sending through GMail (which also has the SMTPUTF8 extension active) had no problems.
So far I haven't debugged the SmtpClient reference sources yet to see what gets sent to the Office365 server. The root cause could thus either be that SmtpClient sends a good message which Office365 "corrupts" before relaying and which GMail sends on without issue; or SmtpClient builds a bad message / SMTP session which Office365 silently accepts and forwards to remote SMTP servers but which GMail accepts and fixes on the fly before relaying.
Either way, I pulled in the MailKit and MimeKit libraries using NuGet and use those instead to send my e-mails. These offer SMTP protocol logging to troubleshoot issues and appear to solve the stated problem by properly sending the SMTPUTF8 and 8BITMIME flags as defined in RFC 6531. It does take extra work to read configuration from the usual Web.config or App.config location but the libraries do the job.
If you want to keep using SmtpClient then you should either contact Microsoft (it's their service and their .NET Runtime), or run your own private SMTP server without the SMTPUTF8 extension which relays to remote servers. In the latter case SmtpClient should properly encode all headers and payload (though it does mean that you might be unable to use the International value for the DeliveryFormat property when you want to send to people with an internationalized e-mail address).
Set the encoding of the mail message so one that supports the characters you use, since the default is us-ascii:
mailMsg.BodyEncoding = Encoding.UTF8;
We had the same Issue with Office365 SMTP Server, using vmime library. We solved it by disabling SMTPUTF8, thus always encoding non-ascii characters.
As stated above by JBert, the same protocol works with GMail SMTP servers.

creating smtp server and read the emails c#

I am given a task to create a new smtp mail server which can receive mail using C#.
While going through the articles i read we can send emails via SMTP but we have to receive or read using POP.
I was directed to links by some stackoverflow already existing questions:
Rnwood and sourceforge
Rnwood I am sorry but i did not understand how to use it.
source forge the msi asked to download if we run it, it asks to download framework 1.1.4322 which will not install in my system and throw error.
Usually there are codes for sending messages so I tried msdn example
I used localhost as the server and 587 as the port.
which gives me error (for any port 587,25)
I also found an article here which actually monitors the localhost and specified port when I try to run the msdn code.
But still I am unable to send email to test in any way.
So is there any way I can code to set up smtp in my own server and receive email and test.
Setting up and configuring a mail server is a completely different ball game than just sending or reading emails from an existing IMAP / POP3 server.
A mail server consists of a number of components such as:
A Mail Transfer Agent (MTA) that handles SMTP traffic and which is responsible for sending email from your users to an external MTA and to receive email from an external MTA.
Mail Delivery Agent which retrieves mail from the MTA and places it in the recipient's mailbox.
A domain name with appropriate DNS records and an SSL certificate.
A server that provides IMAP / POP3 functionality.
In short... stick to publicly available mail servers...
In your post you referenced the SmtpClient from the .NET framework. That library is used to connect to an existing mail server. You can use it like this.
MailMessage message = new MailMessage();
message.From = new MailAddress("your.email.address#example.com", "Your name");
MailAddress recipientsMailAddress = new MailAddress("the.recipients.email#example.com");
message.To.Add(recipientsMailAddress);
message.Subject = "The subject of your email";
message.Body = "The body / content of your email";
message.IsBodyHtml = false; // You can set this to true if the body of your email contains HTML
SmtpClient smtpClient = new SmtpClient
{
Credentials = new NetworkCredential("Your username/email", "Your password"),
EnableSsl = true, // Will be required by most mail servers
Host = "The host name of the mail server", //
Port = 465 // The port number of the mail server
};
smtpClient.Send(message);
If you have a Gmail account, you can use their SMTP server in your C# application, simply use these settings and it should all work.
Hostname: smtp.gmail.com
Port: 587
Username: your_email#gmail.com
Password: ********
RequireSSL: true
Have a look at SmtpListener, I think it does what you want.
It isn't a standard email server which will receive new emails throught SMTP, store them on disk and allow you to retrieve them using POP.
SmtpListener will create a SMTP server that will receive email and allow you to react to any new email through code.
However, please note that you will have to configure it in your production environment like a real SMTP server, including MX DNS entries.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

I am using the SmtpClient library to send emails using the following:
SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from#hostname", "to#hostname", "Subject", "Body");
The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".
I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.
EDIT: Super Redux Version
Try port 587 instead of 465. Port 465 is technically deprecated.
After a bunch of packet sniffing I figured it out. First, here's the short answer:
The .NET SmtpClient only supports encryption via STARTTLS. If the EnableSsl flag is set, the server must respond to EHLO with a STARTTLS, otherwise it will throw an exception. See the MSDN documentation for more details.
Second, a quick SMTP history lesson for those who stumble upon this problem in the future:
Back in the day, when services wanted to also offer encryption they were assigned a different port number, and on that port number they immediately initiated an SSL connection. As time went on they realized it was silly to waste two port numbers for one service and they devised a way for services to allow plaintext and encryption on the same port using STARTTLS. Communication would start using plaintext, then use the STARTTLS command to upgrade to an encrypted connection. STARTTLS became the standard for SMTP encryption. Unfortunately, as it always happens when a new standard is implemented, there is a hodgepodge of compatibility with all the clients and servers out there.
In my case, my user was trying to connect the software to a server that was forcing an immediate SSL connection, which is the legacy method that is not supported by Microsoft in .NET.
Putting this at the beginning of my method fixed this for me
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.
The username is not the username you set up when you've created the sendgrid object in azure. To find your username;
Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
Add the username from SendGrid into your SMTP settings in the web.config file.
Hope this helps!
Change port from 465 to 587 and it will work.
I've tried all the answers above but still get this error with Office 365 account. The code seems to work fine with Google account and smtp.gmail.com when allowing less secure apps.
Any other suggestions that I could try?
Here is the code that I'm using
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "to#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
using (SmtpClient client = new SmtpClient())
{
MailAddress from = new MailAddress(mailFrom);
MailMessage message = new MailMessage
{
From = from
};
message.To.Add(mailTo);
message.Subject = mailTitle;
message.Body = mailMessage;
message.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential
{
UserName = username,
Password = password
};
client.Send(message);
}
UPDATE AND HOW I SOLVED IT:
Solved problem by changing Smtp Client to Mailkit. The System.Net.Mail Smtp Client is now not recommended to use by Microsoft because of security issues and you should instead be using MailKit. Using Mailkit gave me clearer error messages that I could understand finding the root cause of the problem (license issue). You can get Mailkit by downloading it as a Nuget Package.
Read documentation about Smtp Client for more information:
https://learn.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2
Here is how I implemented SmtpClient with MailKit
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "mailto#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailFrom));
message.To.Add(new MailboxAddress(mailTo));
message.Subject = mailTitle;
message.Body = new TextPart("plain") { Text = mailMessage };
using (var client = new SmtpClient())
{
client.Connect(host , port, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}
You may also have to change the "less secure apps" setting on your Gmail account. EnableSsl, use port 587 and enable "less secure apps". If you google the less secure apps part there are google help pages that will link you right to the page for your account. That was my problem but everything is working now thanks to all the answers above.
Answer Specific to Outlook Mailer
var SmtpClient = new SmtpClient{
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential("email", "password"),
Port = 587,
Host = "smtp.office365.com",
EnableSsl = true }
https://admin.exchange.microsoft.com/#/settings
-> Click on Mail Flow
-> Check - Turn on use of legacy TLS clients
-> Save
removing
client.UseDefaultCredentials = false;
seemed to solve it for me.
Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake
If you are using an SMTP server on the same box and your SMTP is bound to an IP address instead of "Any Assigned" it may fail because it is trying to use an IP address (like 127.0.0.1) that SMTP is not currently working on.
To elevate what jocull mentioned in a comment, I was doing everything mention in this thread and striking out... because mine was in a loop to be run over and over; after the first time through the loop, it would sometimes fail. Always worked the first time through the loop.
To be clear: the loop includes the creation of SmtpClient, and then doing .Send with the right data. The SmtpClient was created inside a try/catch block, to catch errors and to be sure the object got destroyed before the bottom of the loop.
In my case, the solution was to make sure that SmtpClient was disposed after each time in the loop (either via using() statement or by doing a manual dispose). Even if the SmtpClient object is being implicitly destroyed in the loop, .NET appears to be leaving stuff lying around to conflict with the next attempt.
Change your port number to 587 from 465
I got the same problem with the .NET smtp client + office 365 mail server: sometimes mails were sent successfully, sometimes not (intermittent sending failures).
The problem was fixed by setting the desired TLS version to 1.2 only. The original code (which started to fail in the middle of the year 2021 - BTW) was allowing TLS 1.0, TLS 1.1 and TLS 1.2.
Code (CLI/C++)
int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType) tls12;
(note: the problem was reproduced and fixed on a Win 8.1 machine)
First Use Port = 587
Generally STARTTLS is required to send mail, Adding the Security Protocol Tls12 will help to resolve this issue.
Secondly test the stmp connection using powershell
$userName = 'username_here'
$password = 'xxxxxxxxx'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
$sendMailParams = #{
From = 'abc.com'
To = 'xyz#gmail.com'
Subject = 'Test SMTP'
Body = 'Test SMTP'
SMTPServer = 'smtp.server.com'
Port = 587
UseSsl = $true
Credential = $credential
}
Send-MailMessage #sendMailParams
Thirdly If this send out the email, Add below code inside SmtpClient function:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Since Jan 22 2022, Google has increased the TLS version requirements Also Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
So we can fix the issue one of the below 2 solutions.
1.By Adding some other Protocols before creating the smtp client >> ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
2.You just need to update the .NET framework version to 4.6 or higher to fix the issue.
In my case, the customer forgot to add new IP address in their SMTP settings. Open IIS 6.0 in the server which sets up the smtp, right click Smtp virtual server, choose Properties, Access tab, click Connections, add IP address of the new server. Then click Relay, also add IP address of the new server. This solved my issue.
If your mail server is Gmail (smtp.google.com), you will get this error when you hit the message limit. Gmail allows sending over SMTP up to only 2000 messages per 24 hours.
I ran into this when using smtp.office365.com, using port 587 with SSL. I was able to log in to the account using portal.office.com and I could confirm the account had a license. But when I fired the code to send emails, I kept getting the net_io_connectionclosed error.
Took me some time to figure it out, but the Exchange admin found the culprit. We're using O365 but the Exchange server was in a hybrid environment. Although the account we were trying to use was synced to Azure AD and had a valid O365 license, for some reason the mailbox was still residing on the hybrid Exchange server - not Exchange online. After the exchange admin used the "Move-Mailbox" command to move the mailbox from the hybrid exchange server to O365 we could use the code to send emails using o365.
If you are using Sendgrid and if you receive this error, it is because Basic authentication is no more allowed by sendgrid.We need to create API key and use them as NetworkCredential. username="apikey" password will be your API key
Reference - https://docs.sendgrid.com/for-developers/sending-email/integrating-with-the-smtp-api
I recently had to set new mail settings on all our applications and encountered this error on multiple projects.
The solution for me was to update the target framework to a newer version on some of my projects.
I also had an ASP.net website project where updating the target framework wasn't enough I also had to add the following code to the web.config <httpRuntime targetFramework="4.8"/>
After trying all sorts of TLS/SSL/port/etc things, for me the issue was this: the username and password I was using for Credentials were not correct, apparently.
Normally our websites use a different set of credentials but this one's were different. I had assumed they were correct but apparently not.
So I'd double check my credentials if nothing else is working for you. What a precise error message!
Try this : Here is the code which i'm using to send emails to multiple user.
public string gmail_send()
{
using (MailMessage mailMessage =
new MailMessage(new MailAddress(toemail),
new MailAddress(toemail)))
{
mailMessage.Body = body;
mailMessage.Subject = subject;
try
{
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Credentials =
new System.Net.NetworkCredential(email, password);
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
mail = new MailMessage();
String[] addr = toemail.Split(','); // toemail is a string which contains many email address separated by comma
mail.From = new MailAddress(email);
Byte i;
for (i = 0; i < addr.Length; i++)
mail.To.Add(addr[i]);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
mail.DeliveryNotificationOptions =
DeliveryNotificationOptions.OnFailure;
// mail.ReplyTo = new MailAddress(toemail);
mail.ReplyToList.Add(toemail);
SmtpServer.Send(mail);
return "Mail Sent";
}
catch (Exception ex)
{
string exp = ex.ToString();
return "Mail Not Sent ... and ther error is " + exp;
}
}
}
In case if all above solutions don't work for you then try to update following file to your server (by publish i mean, and a build before that would be helpful).
bin-> projectname.dll
After updating you will see this error.
as i have solved with this solution.
For outlook use following setting that is not giving error to me
SMTP server name smtp-mail.outlook.com
SMTP port 587
This error is very generic .It can be due to many reason such as
The mail server is incorrect.
Some hosting company uses mail.domainname format.
If you just use domain name it will not work.
check credentials
host name
username password if needed
Check with hosting company.
<smtp from="info#india.uu.com">
<!-- Uncomment to specify SMTP settings -->
<network host="domain.com" port="25" password="Jin#" userName="info#india.xx.com"/>
</smtp>
</mailSettings>
In my case the web server IP was blocked on the mail server, it needs to be unblocked by your hosting company and make it whitelisted. Also, use port port 587.
My original problem is about intermittent sending failures. E.g. First Send() succeeds, 2nd Send() fails, 3rd Send() succeeds. Initially I thought I wasn't disposing properly. So I resorted to using().
Anyways, later I added the UseDefaultCredentials = false, and the Send() finally became stable.
Not sure why though.
SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
There are two solutions. First solution is for app level (deployment required) and second one is for machine level (especially if you use an out-of-the-box / off-the-shelf app)
When we checked the exception, we saw that the protocol is "ssl|tls" depriciated pair.
Since we don't want to deploy, we prefer machine level change (Solution 2).
On August 18, Microsoft announced that they will disable Transport Layer Security (TLS) 1.0 and 1.1 connections to Exchange Online “in 2022.”
https://office365itpros.com/2021/08/19/exchange-online-to-introduce-legacy-smtp-endpoint-in-2022/
Firstly let's check the network (Anything prevents your email sent request? firewall, IDS, etc.)
By using PowerShell check Transport Layer Security protocols
[Net.ServicePointManager]::SecurityProtocol
My Output: Tls, Tls11, Tls12
Test SMTP Authentication over TLS
$HostName = [System.Net.DNS]::GetHostByName($Null).HostName
$Message = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("smtp.office365.com", 587)
$smtp.Credentials = New-Object System.Net.NetworkCredential("me#me.com", "PassMeme");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "sender#me.com"
$Message.Subject = $HostName + " PowerShell Email Test"
$Message.Body = "Email Body Message"
$Message.To.Add("receiver#me.com")
#$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
My output:
There is no error message
If there is any message on your output something prevents your email sent request.
If everything is ok there should be two solutions.
Solution 1:
Application Level TLS 1.2 Configuration (Optional)
Application deployment required.
Explicitly choose TLS in C# or VB code:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
Solution 2:
Machine level TLS 1.2 .NET Framework configuration
Application deployment NOT required.
Set the SchUseStrongCrypto registry setting to DWORD:00000001. You should restart the server.
For 32-bit applications on 32-bit systems or 64-bit applications on 64-bit systems), update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
\Microsoft\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For 32-bit applications that are running on x64-based systems, update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
Wow6432Node\Microsoft\\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For details "How to enable TLS 1.2 on clients" on
https://learn.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-client
Our email service is Azure SendGrid.
Our application stopped sending emails one day, and the error message was "SmtpException: Unable to receive data from the transport connection: net io connectionclosed." We discovered the problem was caused by the fact that our Pro 300K subscription had run out. Emails began to be sent when we upped our subscription.
I was facing the same issue with my .NET application.
ISSUE: The .NET version that I was using is 4.0 which was creating the whole mess.
REASON: The whole reason behind the issue is that Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
FIX: You just need to update the .NET framework version to 4.6 or higher to fix the issue.

C# - Send e-mail without having to login to server

I have an application that needs to send e-mails. Currently, this is what I am using:
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage();
MyMailMessage.From = new System.Net.Mail.MailAddress(fromemail.Text);
MyMailMessage.To.Add(toemail.Text);
MyMailMessage.Subject = subject.Text;
MyMailMessage.Body = body.Text;
System.Net.Mail.SmtpClient SMTPServer = new System.Net.Mail.SmtpClient("smtp.gmail.com");
SMTPServer.Port = 587;
SMTPServer.Credentials = new System.Net.NetworkCredential("email", "password");
SMTPServer.EnableSsl = true;
SMTPServer.Send(MyMailMessage);
Is there a simple way to send an e-mail without having to login to a server? Thank you.
GMail's SMTP server always requires authentication. You may need to setup your own server to send email without authentication.
Configure an SMTP server into your local network (behind a firewall to avoid being a spam source) and use it directly. You can create one in IIS.
There are 2 ways to achieve this:
1) Use your local smtp server (e.g. one with IIS on Win2003/2008 server) and write messages to the local pickup queue). This is possible with minimal changes.
2) You need to resolve the target smtp server. For example when you want to send an email to somebody at msn.com, you'll need to get the MX record for msn.com, e.g. something like mx1.msn.com. You can then directly connect to this SMTP server and send your email to the (local) recipient. Note that there are no built-in ways to resolve the MX-host in .NET (in the sense there are no methods on the Dns class to accomplish this) - you need to do it "manually". Also most SMTP hosts will reject connections from home/residential IP addresses.
You need an SMTP server that does not require authentication, however to stop it being a SPAM server, it needs some other kind of protection like a firewall.

Categories