I'm developing a console app which will be executed from a windows service that needs to send emails using the domain account associated to the domain account running the windows service.
In my development machine I'm logged with a domain account that belongs to the same domain that will run the windows service but I'm not able to get it working properly.
For this development I'm using .NET 4.6.1 and the nuget package FluentEmail.Smtp
My code looks like this:
Email.DefaultSender = new SmtpSender(new SmtpClient
{
UseDefaultCredentials = true,
EnableSsl = true,
Host = "smtp.office365.com",
TargetName = "STARTTLS/smtp.office365.com",
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network
});
await Email.From("myname#mycompanydomain.com", "Some tittle")
.To(emailListObject)
.Subject("Some subject")
.Body("Some body", true)
.SendAsync();
With this code I'm getting the following exception:
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 52.96.9.178:587
at System.Net.Mail.SmtpConnection.ConnectAndHandshakeAsyncResult.End(IAsyncResult result)
at System.Net.Mail.SmtpTransport.EndGetConnection(IAsyncResult result)
at System.Net.Mail.SmtpClient.ConnectCallback(IAsyncResult result)
Note: From my machine I'm able to ping the IP mentioned in the exception
I'll appreciate your assistance
For starters you might want to take a look at the official document - direct send. You will note that there are quite a few issues (such as TLS security) alongside proper configuration of your Exchange server.
Without more information in your question it is rather limited as to what can be answered, however as an alternate solution, maybe take a look at direct send. (which is much less effort).
Settings for direct send
Enter the following settings on the device or in the application directly.
Server/smart host. Use your MX endpoint, for example, contoso-com.mail.protection.outlook.com
Port. Use port 25
TLS/StartTLS. Enable this.
Email address. Use any email address for one of your Office 365 accepted domains. This email address does not need to have a mailbox.
Microsoft recommends adding an SPF record to avoid having messages flagged as spam. If you are sending from a static IP address, add it to your SPF record in your domain registrar's DNS settings as follows:
DNS entry Value
SPF v=spf1 ip4:<Static IP Address> include:spf.protection.outlook.com ~all
I am working in Visual Studio 2012, On Windows 7, I run the program on a Windows Server 2008 R2 machine, both are 64-bit. I have been using the same code in many processes and I always has worked fine. However, recently when I use the same code now I get the following exception,
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: An attempt was made to access a socket
in a way forbidden by its access permissions xxx.xxx.xxx.xxx:25
And the code,
public static void emailReport(string to, string from, string subject,
string body, string attachment, string hostAddress)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(hostAddress);
foreach (string email in to.Split(','))
mail.To.Add(new MailAddress(email));
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpServer.Send(mail);
}
Older processes that use this exact code still work and can send
mail, using the same host address and port.
Looking at the sockets
with netstat -o, I can see that the socket is not being held by any
process.
.net Framework 4.5 is on both my local machine and the server.
I have Visual Studio 2012 on the server and have tried recreating the project there to see if there is any change, there wasn't.
I can connect, on the server, to the mail host using telnet smtp.mydomain.com 25
Essentially starting this week any new versions of applications (.exe) using this code don't send email, but old versions of the same applications do.
I suspect this is a problem with the environment I am running the process in or perhaps the way I am building the project. I am not sure how to fix this problem.
I was finally able to figure this out. It was in-fact a firewall issue despite processes working some of the time.
The firewall had certain criteria to block suspicious file names. I needed to rename the executable to something not suspicious or more reflective of what it does (i.e. "emailer")
I am trying to use System.Net.Mail for an application to send an email, but get this exception:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: No connection could be made
because the target machine actively refused it 198.238.39.170:25
The code I am using is:
string mailserver = "Scanmail.ofm.wa.lcl";
MailMessage msg = new MailMessage("albert#einstein.net", "snark#snarky.com", "Very subjective", "A message body!");
SmtpClient client = new SmtpClient(mailserver);
client.Send(msg);
Obviously the email addresses above are fictional, but in the actual code it uses real email addresses in the system. The mail server address is accurate.
I am tempted to think that I need to put some kind of security credentials in there, but not sure where - although #Andre_Calil's advice suggests this is not the problem, and that possibly the mail server is configured to prevent my development machine from connecting. So how is this to be overcome?
So, as we were talking, your server is probably configured to deny relay from every machine, which is a recommended security setting.
From your development machine, open a prompt (command) and type telnet SMTP_SERVER_IP_ADDRESS 25. This command will try to stablish a basic socket connection on port 25, which is the default SMTP port. If it's successful, you'll still have to discover whether the server requires authentication.
However, if it's unsuccesful, you'll have to put your code on hold until you can get the help of a sysadmin.
One other thing to try is to repeat this same test from a app server, because the SMTP server may be configured to allow app_server and deny everybody_else.
Regards
I was trying to impliment an email option in my program..
The follwing exception was thrown
+$exception {"The server rejected one or more recipient addresses. The server response
was: 550 5.7.1 <"mail-id">... Relaying denied. IP name lookup failed [172.25.9.23]\r\n"}
System.Exception {System.Web.HttpException}
This is what i have done......
MailMessage objEmail = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCC.Text;
objEmail.Subject = txtSubject.Text;
objEmail.Body = txtBody.Text; ;
objEmail.Priority = MailPriority.High;
WebMsgBox.Show("test");
SmtpMail.SmtpServer = "someserver.com";
MailAttachment attach = new MailAttachment(#"D:\email.txt");
objEmail.Attachments.Add(attach);
try
{
SmtpMail.Send(objEmail);
WebMsgBox.Show("Your Email has been sent sucessfully - Thank you");
}
catch (Exception exc)
{
WebMsgBox.Show("Send failure: " + exc.ToString());
}
Perhaps check that the server you are using to send with (smtp) has the sender machine IP whitelisted. I don't actually know how this is done but your infrastructure folks could help. Seems as though the smtp server has been secured somewhat.
When we try to send mail, there are lots of configuration settings have to be ok including some background things. (mailserver, antivirus, firewalls,routers, anti spyware etc…). Have you checked your SMTP server (services) is enabled or not ?
I am not sure 100% that below steps solve your problem, but you can check your SMTP server configurations by it :
In the Control Panel >> Administrative Tools >> Internet Information Services.
Open the node for your computer, right-click the Default SMTP Virtual Server node and choose Properties.
In the Access tab, click Connection.
Select Only the list below, click Add and add the IP 127.0.0.1. This restricts connections to just the local computer, i.e., localhost. Close the Connection dialog box.
Click Relay and repeat Step 4 to allow only localhost to relay through this server.
For IIS7, you can do it by :
Open IIS and select the node for your computer, double click on "SMTP Email" option at right side panel.
You can set SMTP server and port details there.
In your firewall or router (or both), close incoming port 25. This is an important security measure that will prevent spammers from finding your SMTP server and using it to relay spam.
Hope this will solve your problem.
Unable to test sending email from .NET code in Windows Vista Business.
I am writing code which I will migrate to an SSIS Package once it its proven. The code is to send an error message via email to a list of recipients.
The code is below, however I am getting an exception when I execute the code.
I created a simple class to do the mailing... the design could be better, I am testing functionality before implementing more robust functionality, methods, etc.
namespace LabDemos
{
class Program
{
static void Main(string[] args)
{
Mailer m = new Mailer();
m.test();
}
}
}
namespace LabDemos
{
class MyMailer
{
List<string> _to = new List<string>();
List<string> _cc = new List<string>();
List<string> _bcc = new List<string>();
String _msgFrom = "";
String _msgSubject = "";
String _msgBody = "";
public void test(){
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#domain.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";
mail.IsBodyHtml = false;
//send the message
SmtpClient smtp = new SmtpClient();
smtp.Host = "emailservername";
smtp.Port = 25;
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
}
Exception Message
Inner Exception
{"Unable to read data from the transport connection: net_io_connectionclosed."}
Stack Trace
" at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)\r\n at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)"
Outer Exception
System.Net.Mail.SmtpException was unhandled
Message="Failure sending mail."
Source="System"
StackTrace:
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at LabDemos.Mailer.test() in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Mailer.cs:line 40
at LabDemos.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Program.cs:line 48
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IO.IOException
Message="Unable to read data from the transport connection: net_io_connectionclosed."
Source="System"
StackTrace:
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
InnerException:
There are several things that can cause this problem, and here are some of the things that I've found.
Questions: You mention "Exchange" -- Is this an exchange server? Does the host require authentication (maybe you need to add authentication to the client)? What I would try doing first is assigning the host to the static IP address instead of the host name to see if that works first. If it does then it's most likely a problem with the DNS mapping.
If you are running your exchange server with Virtualization, you need to configure the SmtpClient to the host IP of the Virtual Server, not the physical hosting server name or IP. Right click on Default SMTP virtual server, select Properties, then go to Access tab, click Relay then add the IP address of the computer that send SMTP request to the SMTP server. (ASP.net site)
If this doesn't work, it's because the server is blocking you from sending SMTP packets. You need to make sure to add the box you are sending the SMTP messages from to the SMTP server. This is done through IIS's authentication tab.
I would also like to point out that you should dispose the mail client, or use the client in a "using" statement. This will make sure that the "QUIT" is sent to the server and gracefully close the connection.
using(SmtpClient smtp = new SmtpClient())
{
smtp.Host = "emailservername";
smtp.Port = 25;
smtp.UseDefaultCredentials = true;
smtp.Send(mail)
}
Restart IIS. I know this sounds silly, to do a restart for everything. (and sorry to bump up an old thread). But sometimes restarting IIS works magic. I faced the exact same issue and restarting solved it.
Might have happened cause temporarily the name 'localhost' couldn't be resolved. I;m just posting here so that someone who faces it now will probably try this quick fix before attempting to investigate further. Hope it helps
If you've specified an IP address in the SMTP Service settings then make sure you're specifying that IP address of the machine within IIS7 and not putting localhost.
IIS7 makes it easy to select 'localhost' but that will lead to this error if the IP for instance is 10.0.0.1
If you are using localhost (Use Localhost) in IIS 7, then change it to IP address of the machine instead of localhost or 127.0.0.1
Also follow below link to update your mail server relay accordingly:
Mailbox unavailable. The server response was: 5.7.1 Unable to relay for abc#xyz.com
Vista and Windows 7 does not have any SMTP server, this facility has been removed since Windows XP, so you need to setup your SMTP server explicitly, several tools are available in market for that, you can check that out.
Also once you configure the SMTP, remember to check the server name which you would be using to send the e-mail.
I had the same issue since I had multiple IP on my server (Virtual Servers) and my host was pointing to localhost while my SMTP Virtual Server was assigned to one particular IP:
<smtp deliveryMethod="Network">
<network host="localhost" port="25" defaultCredentials="false"/>
</smtp>
There are 2 solutions for this:
Change your code and set host to the particular IP that is being used by SMTP Virtual Server instead of localhost.
Change SMTP Virtual Server IP to All Unassigned
To see/change SMTP Virtual Server IP:
Right click on Default SMTP virtual server, select Properties, on General tab change/see IP address.
Hope this saves someone's day with the same issue.
I have found that the Vista Business OS does not come with IIS SMTP. I suspect this is the missing piece of the puzzle. Has anyone had any luck with this issue?
Is your code incompleted.Dash is correct in identifying it.Other then that check smtp component is installed or not
check link text
I am facing this issue last 6hr and I am new on that so I am trying to solve this issue in following way
1) I opened command prompt (e.g. Ctrl + R type cmd and enter).
2) And check to SMTP server ping and check response.
3) If it’s gets response then it’s ok and to move next step 4 other wise smtp name is wrong.
4) Then I check by telnet smtp port (e.g. 25 ) is open or not.
5) Using this cmd we check the SMTP response.
6) telnet "yoursmtpname" "portno” (e.g. telnet smtp.gmail.com 25)
7) If telnet is not working, please install or add from control panel in add new features.
8) If it’s working then it’s pass result like.
9) 220 mx.google.com ESMTP .
Using above steps we can find out smtp connection is ready or not to sending mail.
I developed a Windows Service application in VB using .NET Framework v4.5 and recently ran into this issue.
First, a little background - I ran into the OP's error after trying to deal with the error "Service not available, closing transmission channel. The server response was: Error: too many messages in one session" which was resolved by calling the Dispose method on the SmtpClient object after each email sent. Just to be ultra safe, I also called Dispose on the MailMessage object.
Okay, so now the 'too many messages in one session' issue is resolved but now I occasionally got the 'Unable to read data from the transport connection: net_io_connectionclosed' error. Awesome. Turns out I had not implemented my email class consistently - in one instance, it was being disposed of while in the other it was not.
Here's an example of what resolved both issues for me (it's in VB but you get the idea):
With New clsEmail(True)
With .Message
.To.Add("user#domain.com")
.Subject = msgSubject
.Body = msgContents
End With
.Server.Send(.Message)
.Server.Dispose()
.Message.Dispose()
End With
My email class has, among other things, has 2 properties - Message (System.Net.Mail.MailMessage) and Server (System.Net.Mail.SmtpClient) which is what's being disposed in this example.
I haven't had a single problem after hundreds of emails once every single instance that sends email in my service was implemented in this way.
upgrade to .NET 4.0 and apply all security updates
I was facing the same issue for one month. I tried all the possible solutions provided on Microsoft's official site. Finally, I found the root cause of it.
I have updated targetFramework from 4.5.2 to 4.6.1 in web.config file.
compilation debug="true" targetFramework="4.6.1"
httpRuntime maxRequestLength="183500800" executionTimeout="3600" targetFramework="4.6.1" enableVersionHeader="false"
the above solution worked for me, and now my emails are triggering successfully from the application.