Sending email through SMTP fails : MailBox name not allowed - c#

I am trying to send an email through an SMTP server but it fails giving me the following error:
MailBox name not allowed. The server response was Senders must have
valid reverse DNS
Unfortunately I could not find meaningfull information to solve the problem
Here is my method:
public void SendSmtp()
{
try
{
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("some#email.com");
message.To.Add(new MailAddress("other#email.com"));
message.Subject = "subject";
message.Body = "body";
message.IsBodyHtml = true;
// NetworkCredential basicCredential = new NetworkCredential("test#test.com", "password");
try
{
using (SmtpClient client = new SmtpClient())
{
client.Host = "mail.host.com";
client.Port = 25;
client.UseDefaultCredentials = true;
// client.Credentials = basicCredential;
client.Send(message);
MessageBox.Show("Success!!");
}
}
finally
{
//dispose the client
message.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//client.Send(message);
}
else
{
Console.WriteLine("Failed to deliver message to {0}",
ex.InnerExceptions[i].FailedRecipient);
}
}
}
}
This works well when I try it on a different server or my local machine not sure why.
I set up my SMTP grant access to my server.
Please advice.

The error's a direct response from the SMTP server that your code is attempting to connect to. Your client machine does not have a valid reverse DNS mapping (e.g. 127.0.0.1 -> localhost), so the SMTP server is rejecting the connection.
It could be something as simple as your client identifying itself as example.com, but when the SMTP server does a reverse lookup, the server's IP comes back as system-1-2-3.4.hostingprovider.com or similar.

Looking back at my question, I can tell you that if you face this issue, It is not an issue in the code really it is more of a network issue.
A quick way to test this is to do run your code in a less locked down environment. I was getting this error only on my production server. It worked fine in development.
So this means you need to close visual studio and investigate. The error could be misleading so don't rely on it 100% instead use tools to debug your issue. I used wireshark to examine the packets and I noticed an IP that being denied on my SMTP server.
I didn't realize because my server had multiple network cards in my case. Something that I could not easily guessed. So my advise is to use tools to watch traffic network and you will find the reason.
Don't guess, use tools* to give you the answers.
*tools: in addition to wireshark, sites like mxtoolbox could be very helpful

Old thread, but if anybody else has this issue, for me the issue was related to the "FROM" attribute. On the smtp server there is allowed "from" address which you have to request to your email server admins.

Related

SMTP 5.7.57 error when trying to send email via Office 365

I'm trying to set up some code to send email via Office 365's authenticated SMTP service:
var _mailServer = new SmtpClient();
_mailServer.UseDefaultCredentials = false;
_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password");
_mailServer.Host = "smtp.office365.com";
_mailServer.TargetName = "STARTTLS/smtp.office365.com"; // same behaviour if this lien is removed
_mailServer.Port = 587;
_mailServer.EnableSsl = true;
var eml = new MailMessage();
eml.Sender = new MailAddress("test.user#mydomain.com");
eml.From = eml.Sender;
eml.to = new MailAddress("test.recipient#anotherdomain.com");
eml.Subject = "Test message";
eml.Body = "Test message body";
_mailServer.Send(eml);
This doesn't appear to be working, and I'm seeing an exception:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
I've tried enabling network tracing and it appears that secure communications are established (for example, I see a line in the log for the "STARTTLS" command, and later there's a line in the log "Remote certificate was verified as valid by the user.", and the following Send() and Receive() data is not readable as plain text, and doesn't appear to contain any TLS/SSH panics)
I can use the very same email address and password to log on to http://portal.office.com/ and use the Outlook email web mail to send and read email, so what might be causing the authentication to fail when sending email programmatically?
Is there any way to additionally debug the encrypted stream?
In my case after I tried all this suggestion without luck, I contacted Microsoft support, and their suggestion was to simply change the password.
This fixed my issue.
Note that the password wasn't expired, because I logged on office365 with success, however the reset solved the issue.
Lesson learned: don't trust the Office 365 password expiration date, in my case the password would be expired after 1-2 months, but it wasn't working.
This leaded me to investigate in my code and only after a lot of time I realized that the problem was in the Office365 password that was "corrupted" or "prematurely expired".
Don't forget every 3 months to "refresh" the password.
To aid in debugging, try temporarily switching to MailKit and using a code snippet such as the following:
using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MailKit;
using MimeKit;
namespace TestClient {
class Program
{
public static void Main (string[] args)
{
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("", "test.user#mydomain.com"));
message.To.Add (new MailboxAddress ("", "test.recipient#anotherdomain.com"));
message.Subject = "Test message";
message.Body = new TextPart ("plain") { Text = "This is the message body." };
using (var client = new SmtpClient (new ProtocolLogger ("smtp.log"))) {
client.Connect ("smtp.office365.com", 587, SecureSocketOptions.StartTls);
client.Authenticate ("test.user#mydomain.com", "password");
client.Send (message);
client.Disconnect (true);
}
}
}
}
This will log the entire transaction to a file called "smtp.log" which you can then read through and see where things might be going wrong.
Note that smtp.log will likely contain an AUTH LOGIN command followed by a few commands that are base64 encoded (these are your user/pass), so if you share the log, be sure to scrub those lines.
I would expect this to have the same error as you are seeing with System.Net.Mail, but it will help you see what is going on.
Assuming it fails (and I expect it will), try changing to SecureSocketOptions.None and/or try commenting out the Authenticate().
See how that changes the error you are seeing.
Be sure you're using the actual office365 email address for the account. You can find it by clicking on the profile button in Outlook365. I wrestled with authentication until I realized the email address I was trying to use for authentication wasn't the actual mailbox email account. The actual account email may have the form of: account#company.onmicrosoft.com.
We got ours working by converting the mailboxes (from address) from "shared" to "regular". Before this change, my application quit sending email when we migrated from Gmail to Office 365. No other code changes were required, besides setting the host to smtp.office365.com.
Please check below code I have tested to send email using Exchange Online:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("YourEmail#hotmail.com", "XXXX"));
msg.From = new MailAddress("XXX#msdnofficedev.onmicrosoft.com", "XXX");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("XXX#msdnofficedev.onmicrosoft.com", "YourPassword");
client.Port = 587; // You can use Port 25 if 587 is blocked
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception ex)
{
}
Port (587) was defined for message submission. Although port 587 doesn't mandate requiring STARTTLS, the use of port 587 became popular around the same time as the realisation that SSL/TLS encryption of communications between clients and servers was an important security and privacy issue.
In my case my problem was not related to the code but something to do with the Exchange mailbox. Not sure why but this solved my problem:
Go to the exchange settings for that user's mailbox and access Mail Delegation
Under Send As, remove NT AUTHORITY\SELF and then add the user's account.
This gives permissions to the user to send emails on behalf of himself. In theory NT AUTHORITY\SELF should be doing the same thing but for some reason that did not work.
Source: http://edudotnet.blogspot.com.mt/2014/02/smtp-microsoft-office-365-net-smtp.html
I got this same error while testing, using my own domain email account during development. The issue for me seemed related to the MFA (Multi Factor Authentication) that's enabled on my account. Switching to an account without MFA resolved the issue.
I had this issue since someone had enabled Security defaults in Azure.
This disables SMTP/Basic authentication. It's clearly stated in the documentation, but it's not evident by the error message, and you have to have access to the account to find out.
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/concept-fundamentals-security-defaults
It's possible to enable it per account.
https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission
You need change the credentials function. Here is the substitution you need to make:
change
-*_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password");*
for this
-*_mailServer.Credentials = new NetworkCredential("test.user#mydomain.com", "password", "domain");*
In my case, password was expired.I just reset password and its started working again

Mailbox unavailable. The server response was: relay not permitted

I am sending emails via an external SMTP server. Sending the email is handled with this code:
try
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.From = new MailAddress(froma);
mail.To.Add(toc);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
SmtpClient smtp = new SmtpClient(ClientServer);
DataSet ds = new DataSet();
int retCode = Email.getSmtp(ref ds, DatabaseName);
string User="";
string Password="";
if (ds.Tables["Value"].Rows.Count > 0)
{
User = ds.Tables["Value"].Rows[0]["UserName"].ToString();
Password = ds.Tables["Value"].Rows[0]["PasswordName"].ToString();
}
else
{
MessageBox.Show("Invalid SMTP settings!");
return;
}
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(User, Password);
smtp.EnableSsl = false;
smtp.Send(mail);
}
catch (System.Web.HttpException exHttp)
{
System.Console.WriteLine("Exception occurred:" + exHttp.Message);
}
Testing this code on my server, with my own SMTP server on the same network, this returns all my emails. However, using an external SMTP server causes the error:
Mailbox unavailable. The server response was: relay not permitted.
I have read around and it appears that the admin for SMTP must allow relays for my server. However, using the authentication credentials provided, I can't seem to connect, and am still receiving the relay error.
Yes, it sounds like the external server that you are using is not allow relay. Even if you have the proper authentication credentials, you will not be able to send the email because the relay function is still disabled. Are you the admin of this external server? If you are then you can enable it. This LINK HERE explains how to set up SMTP and the relay. If you are not the admin of this external server, then you will have to contact who is so they can enable the SMTP and relay for you.
It sounds like the server on your network has SMTP installed and the relay is set up properly since you are able to send. I had to install SMTP and configure the relay on all three of servers here (development box, staging box, and production box) to send emails. I hope this information helps.
I had the same error and commented out :
//smtp.UseDefaultCredentials = true;
And the email was sent successfully.

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

Trying to send mail via SMTP. No mails arrives and no exception error

Problem: Have made a small mail program which works perfectly on my developer pc but when put into production it fails.
protected void Page_Load(object sender, EventArgs e)
{
string smtpHost = ConfigurationManager.AppSettings["SmtpAddress"];
MailMessage mail = new MailMessage();
mail.From = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.Sender = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.To.Add(new MailAddress("zzz#xxx.yy"));
mail.Subject = "Test mail";
mail.Body = string.Format("Is this mail sent via {0} ?", smtpHost);
lblMsg2.Text = string.Format("SmtpHost: {0}", smtpHost); ;
SmtpClient client = new SmtpClient(smtpHost);
try
{
client.Send(mail);
}
catch (Exception exception)
{
lblMsg3.Text = exception.Message.ToString();
lblMsg4.Text = exception.InnerException.ToString();
}
}
I do get the correct mail address and everything on the production server, but nothing ends in my email inbox :-(. I do not receive any exceptions.
I have tried using telnet on the same server and from there I am able to send mails.
I have tried installing WireShark which is looking at the network card on the server and when using telnet I do get the reponse I suspected, but from my program I do not receive anything.
Edited 2012-03-12 # 09:46 danish time
Have now updated the code to look like this
protected void Page_Load(object sender, EventArgs e)
{
string smtpHost = ConfigurationManager.AppSettings["SmtpAddress"];
MailMessage mail = new MailMessage();
mail.From = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.Sender = new MailAddress(ConfigurationManager.AppSettings["FromMailAddress"]);
mail.To.Add(new MailAddress("zzz#xxx.yy"));
mail.Subject = "Test mail";
mail.Body = string.Format("Is this mail sent via {0} ?", smtpHost);
lblMsg2.Text = string.Format("SmtpHost: {0}", smtpHost); ;
SmtpClient client = new SmtpClient(smtpHost);
client.Send(mail);
}
And quite interesting: Even when inserting an SMTP-server that does definately not exist, I still do not get any errors on my production environment. I do get an exception on my developer pc which basically means that the smtp-server does not exist (which I also expected to get a message about).
Case solved :-)
And I learned more about IIS!
The IIS was set up to "Store e-mail in Pickup directory" instead of "Deliver e-mail to SMTP server". Unfortunately I am not that good at IIS and I did not know that there was a setting like that... I am now!
The "double check you configuration settings" from #GarryM was unfortunately not enough for me or my mail-administrator to make us look at the IIS. I am too much a programmer and my mail-adm is too much a network guy :-)
Thank you everyone for your answers. It was partly because of all your good hints and ideas that I could leave out more and more parts.
Double-check the configuration of your mail server. If it isn't throwing an exception then the issue is most likely that the mail has been accepted, but it's not relaying it or potentially treating it as spam.
Some hosting providers also silently block some of the larger free mail hosts due to spam issues, if you are using a shared hosting provider it's worth asking them too.
Also have you tried running the same code locally but pointing at the live mail host? (Providing you can access it externally) That way you can step-through the code and ensure that an exception isn't getting thrown.
It would help if you removed the try/catch as this will allow any exception to propagate up.
Another thing to try is client.EnableSSL if you are using a secure connection, which many mail servers require.

How can i disable the relaying and use my code as an authenticated client?

So there are many posts on this error i'm getting. But most deal with IIS.
Mailbox unavailable. The server response was: 5.7.1 Unable to relay
I have ported my code to console to see if i still get this error, and i do. It would seem as though it's still using ISS as a relay or something even though this is a console application?
I have spoken to the Exchange Admin and he is not going to open up the mail server for any relaying or allow my server to do so. So i would like to make my C# code send out the email as a regular authenticated client as if it were outlook.
My code below works if i'm sending it to someone within my own domain but not if the recipient is outside the domain.
How can i disable the relaying and use my code as an authenticated client so i can send emails to people outside my domain?
CODE:
static void Main(string[] args)
{
Console.WriteLine("Sending Mail...");
try
{
SmtpClient _SMTPServer = new SmtpClient("companymailserver", 587);
_SMTPServer.Credentials = new System.Net.NetworkCredential("myusername", "mypassword");
MailMessage _mailMessage = new MailMessage();
_mailMessage.To.Add(new MailAddress("someone#gmail.com"));
_mailMessage.From = new MailAddress("myself#mycompanydomain.com");
_mailMessage.IsBodyHtml = false;
_mailMessage.Subject = "This is a test";
_mailMessage.Body = "This is the body";
_SMTPServer.Send(_mailMessage);
}
catch (Exception err)
{
Console.WriteLine("error: " + err.Message);
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
UPDATE #1
The strange thing is no matter what credentials i put i get the same 'Unable to relay' error. As if it's defaulting to relay and ignoring my SmtpClient settings.
I'm guessing that the authentication failed. Try including the domain name.
_SMTPServer.Credentials =
new System.Net.NetworkCredential("myusername", "mypassword", "mydomain");
Also, be sure to set UseDefaultCredentials to false
_SMTPServer.UseDefaultCredentials = false;

Categories