"SmtpFailedRecipientException: Mailbox unavailable" when mailbox is available - c#

I get this error when I try to send an e-mail to a specific address in my code:
System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: Unknown user
The code sends an e-mail to two email addresses, mine and my colleague's. The e-mail sends to me just fine, but I get that error when it tries to send the email to him.
I looked around, and basically the common explanation for this error is that the email address is invalid, or their mailbox is full and isn't allowed to receive mail, or there is some setting on the server that is restricting it from receiving an e-mail.
But the email address is able to receive email, I'm corresponding back and forth through e-mail with him right now.
Is there any other reason why this error might occur?
EDIT:
Here's the code, maybe someone can spot an issue. I checked the parameters being passed, all the data is correct:
private static void SendEmail(IEnumerable<MailAddress> to, MailAddress from,
string subject, string body, string bodyHtml)
{
var mail = new MailMessage { From = from, Subject = subject };
foreach (var address in to)
{
mail.To.Add(address);
}
mail.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(bodyHtml, null, "text/html"));
mail.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(body, null, "text/plain"));
try
{
var smtp = new SmtpClient("localhost", 25)
{
Credentials = new NetworkCredential("xxx", "xxx")
};
smtp.Send(mail);
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
}
}

Assuming your SMTP settings are correct this is most probably a case of a server-side restriction...
For example to prevent spam the server only accepts smtp from static sender IP and/or is checking sender IP against MX records (DNS) etc.

Related

Problem with SmtpClient in ASP.NET web app

I am having an issue with SmtpClient in an ASP.NET web application.
I have a generic function that builds an email message and then sends it. The code is as follows:
public static bool SendMessage( string fromName, string toName, string subject, string body ) {
var smtpClient = new SmtpClient("server address here")
{
Port = 587,
Credentials = new NetworkCredential("user", "pass"),
EnableSsl = false,
};
var mailMessage = new MailMessage
{
From = new MailAddress("sender", "Testing"),
Subject = subject,
Body = body
};
mailMessage.To.Add ( new MailAddress(toName, "Valued Customer") );
try {
smtpClient.Send ( mailMessage );
return true;
}
catch (Exception ex) {
var error = $"ERROR :{ex.Message}";
return false;
}
}
The problem is, I get the following error when I call it:
Mailbox unavailable. The server response was: <email address being sent to> No such user here
Naturally I removed the value in the < >, but in the original error message it is the email address of the recipient. I almost think the SMTP server believes the recipient has to be a user on the system.
What can I try next? I even hard-coded email addresses in rather than using variables, thinking maybe there was some weird issue with that, but it didn't work.
The error is telling you that the the SMTP server does not have a user with that email address (usually it has to do with security around the FROM address). The SMTP server will not send email if it does not recognize the FROM address.
Solution, change your FROM. Example:
var mailMessage = new MailMessage
{
From = new MailAddress("tester", "test#adminsystem.com"),
Subject = subject,
Body = body
};

SmtpFailedRecipientException not thrown from SmtpClient.Send(MailMessage)

I am trying to send an email to a fake email address and get a SmtpFailedRecipientException, however when I send the email to a fake address on my company domain, no exception is thrown. I am developing in VS2015 with .NET 4.5.2 and running the console application on a Windows 7 environment.
This code works correctly and sends emails when the email addresses are valid, and it will even throw a SmtpFailedRecipientException when I try sending to an invalid gmail or hotmail address. It seems that the only time an exception isn't thrown is when I try to send to a fake address within my company domain. Our company uses Office365 and I get an 'Undeliverable' message in my inbox when I try to send to the fake address from my address.
Does anyone have an idea why this is happening? I suspect it might be a setting on the mail server, but I dont have access to the mail server to check and see. I also might just be missing something obvious and be making a rookie mistake.
// Initialize SMTP client
SmtpClient client = null;
try
{
string from = "myEmailAddress#mycompany.com", to = "fakeEmailAddress#mycompany.com";
// Build client
client = new SmtpClient("mail.mycompany.com");
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// Create message
using (MailMessage message = new MailMessage(from, to)
{
Subject = "Test email to fake address",
Body = "This email won't be sent"
})
{
// Send message
client.Send(message);
}
}
catch (SmtpFailedRecipientException ex)
{
Console.WriteLine($"SmtpFailedRecipientException caught.{Environment.NewLine}{ex.ToString()}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught.{Environment.NewLine}{ex.ToString()}");
}

Getting a Mailbox unavailable. Too many invalid recipients error

Our application sends out emails using the
new SmtpClient(smtpServer).Send(message);
We are making sure that the smtpServer is valid, the message has To and From addresses, a subject and a body. If any of these are missing, we would log an exception before even attempting to send a message.
But the application frequently fails with the below exception.
Email Fail: System.Net.Mail.SmtpException: Mailbox unavailable. The server response was: Too many invalid recipients.
Now, please note that the email send functionality is not failing always. For the same "To" address, it fails, may be about half the times. So, if the application tries sending out emails 100 times, we are getting some 40+ failures with the same message.
I have already validated that the To address and the From address exists. We are seeing this issue since last month when we shifted from Outlook to Gmail.
Here is the code.
if (fromAddress.Length == 0)
fromAddress = Resources.FromAddress;
if (toAddress.Length == 0) return "To Address is Required.";
if (smtpServer.Length == 0)
smtpServer = Resources.SMTPServer;
if (string.IsNullOrEmpty(smtpServer))
return "SMTP sever not specified";
MailMessage mailMessage = new MailMessage();
//set the addresses
mailMessage.From = new MailAddress(fromAddress);
string[] toAdds = toAddress.Split(';');
short i = 0;
foreach (string address in toAdds)
{
if(i==0) mailMessage.To.Add(address); else mailMessage.CC.Add(address);
i++;
}
if (!string.IsNullOrEmpty(bcc))
{
string[] bccAddresses = bcc.Split(';');
foreach (string address in bccAddresses)
{
mailMessage.Bcc.Add(address);
}
}
if (!string.IsNullOrEmpty(cc))
{
string[] ccAddresses = cc.Split(';');
foreach (string address in ccAddresses)
{
mailMessage.CC.Add(address);
}
}
if (subject.Length > 0)
mailMessage.Subject = subject;
mailMessage.Body = sBody;
mailMessage.IsBodyHtml = true;
SmtpClient emailClient = new SmtpClient(smtpServer);
emailClient.Send(mailMessage);
Any directions?
If the same email with the same sender and recipients is sometimes accepted, sometimes rejected by the SMTP server, it may be the result of a server antispam policy. For example :
Directory Harvest Attack Prevention (DHAP) : which causes a "550 Too many invalid recipients" error when exceeding a number of RCPT TO commands over a given period of time.
Quotas : a limit on the number of mails that a mailbox/IP can send per minute/second to prevent spamming.
You can validate if the SMTP server settings are the cause of your problem by (temporarily) :
whitelisting the IP address of your SMTP client
disabling any quota/antispam Policy applied to your sender's mailbox
If that doesn't solve your problem, then use a tool like WireShark to record the SMTP dialog and check exactly what email addresses are sent in the RCPT TO command, and in which cases the SMTP Server rejects them. Then, post it here.

How to send mails using SmtpClient and DefaultNetworkCredentials to a distribution list that only allows authenticated senders?

I'm trying to send automated emails from a C# console application from machines to clients all on the same domain via our internal Exchange 2007 server (using SMTP), but I'm hitting a snag with distribution lists that only allow authenticated senders. Basically the mails I'm sending are getting rejected by Exchange with:
#550 5.7.1 RESOLVER.RST.AuthRequired; authentication required ##rfc822;AuthTESTGroup#example.com
I'm using System.Net.Mail.SmtpClient and setting the Credentials property to System.Net.CredentialCache.DefaultNetworkCredentials, but somewhere along the line, the credentials of the account running this program (me, a valid domain user with a valid mailbox) are not getting passed down to Exchange correctly.
I'm using System.Net.CredentialCache.DefaultNetworkCredentials because I do not want to hard code a username or password (either in the code itself or in any sort of configuration file); I want the process to authenticate with our SMTP server using Windows authentication.
Here is a test program I've been using to reproduce the problem (domain names have been anonomized):
using System;
using System.Net.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var smtpClient = new SmtpClient
{
Host = "MAIL",
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
};
var mailMessage = new MailMessage
{
Body = "Testing",
From = new MailAddress(Environment.UserName + "#example.com"),
Subject = "Testing",
Priority = MailPriority.Normal
};
mailMessage.To.Add("AuthTESTGroup#example.com");
smtpClient.Send(mailMessage);
}
}
}
Whenever I run this as myself (again, I'm a valid user on the domain, with an existing mailbox on the Exchange server) I get an undeliverable bounce message from Exchange with the response:
#550 5.7.1 RESOLVER.RST.AuthRequired; authentication required ##rfc822;AuthTESTGroup#example.com
I talked to our Exchange server admin and he saw the following error from the Exchange server's event log:
Account For Which Logon Failed:
Security ID: NULL SID
Account Name:
Account Domain:
Failure Information:
Failure Reason: Unknown user name or bad password.
Status: 0xc000006d
Sub Status: 0xC0000064
Apparently that status code and sub status code translate to:
0xc000006d This is either due to a bad username or authentication information. Usually logged as status code with 0xc0000064 as substatus
0xC0000064 user name does not exist
So again, it's as if somewhere along the line, my Windows credentials are not getting passed down to the Exchange server even though I'm setting the SmtpClient.Credentials to System.Net.CredentialCache.DefaultNetworkCredentials
Any ideas?
Thanks in advance!
you need to pass username, password
here is a code snippet of how I would do it... keep in mind this is a code snippet you need to make the necessary changes to fit your Use Case
MailClient = new SmtpClient();
MailClient.Credentials = new System.Net.NetworkCredential(username, password);
below is another example but uses the server variable.. this maybe what you need to do try and let me know the server for example you can pass as your domain.com
example :
//SmtpClient client = new SmtpClient("smtp.contoso.com");//this would be server
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
public static void CreateBccTestMessage(string server)
{
MailAddress from = new MailAddress("ben#contoso.com", "Ben Miller");
MailAddress to = new MailAddress("jane#contoso.com", "Jane Clayton");
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the SmtpClient class.";
message.Body = #"Using this feature, you can send an e-mail message from an application very easily.";
MailAddress bcc = new MailAddress("manager1#contoso.com");
message.Bcc.Add(bcc);
SmtpClient client = new SmtpClient(server);
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an e-mail message to {0} and {1}.",
to.DisplayName, message.Bcc.ToString());
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
ex.ToString());
}
}

Permission issues when trying to send email via SMTP from ASP.NET page

I have done this before without any issue but now I don't know what's wrong. I have a web page with a button for email which I want to send some data to email addresses with.
I asked our web hosting company for server details and the response I got was:
"You can use the following details for mail.
Incoming mail server: mail.ourSite.com Outgoing mail server: mail.ourSite.com
Username and password are the email address and password associated with the email address.
"
I am not sure about the last line but I created a new email address in the web host's control panel.
The code I use is:
// instantiate a new mail definition and load an html
// template into a string which I replace values in
// then the rest of the code below
md.Subject = String.Format("{0} {1} {2}", emailSubject, firstName, lastName);
MailMessage msg = md.CreateMailMessage(emailAddress, replacements, emailBody, new Control());
md.IsBodyHtml = true;
SmtpClient sc = new SmtpClient(emailServer);
sc.Credentials = new NetworkCredential(emailUsername, emailPassword);
try
{
sc.Send(msg);
}
emailServer - mail.ourSite.com (dummy value in this post)
emailUsername - the email address I created in the control panel
emailPassword - the password for the email above
The error I have is that when I send emails to other domains than our own I get
"Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server."
When I email to an address within our host then it works fine.
The support is not very supportive so I am asking here what you might think the problem could be? I find it strange that I use the password for an email address I created, should it really be like that?
I think that you are using the wrong email address for the NetworkCredential. It should be the one for your email account that you got from the one providing emailServer.
Try this ..
msg.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("Email", "Password");
msg.Credentials = MyCredential;
here is code to send mail..
i hope i will helpful to you..
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}

Categories

Resources