Mailbox unavailable. The server response was: 5.7.1 Unable to relay - c#

Same ASP.NET MVC 4 website, same mail send code. Sending e-mail messages from AccountController is not working anymore, from all the other controllers it is.
Here is the error I get from AccountController actions:
Cannot send e-mail from noreply#domain.com to bill#microsoft.com
Exception: Mailbox unavailable. The server response was: 5.7.1 Unable to relay.
mail.domain.com, SMTPSVC/mail.domain.com, 25,
What should I check? It worked from years but with a recent Windows Server 2008 / Exchange 2010 update is not working anymore.
MailMessage message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = isHtml
};
try
{
smtpClient.Send(message);
string errorMsg = "Sending e-mail from " + fromAddress.Address + " to " + originalAddresses[i];
errorMsg += Environment.NewLine;
errorMsg += smtpClient.Host + ", " + smtpClient.TargetName + ", " + smtpClient.Port + ", " + smtpClient.ClientCertificates + ", " + smtpClient.EnableSsl + ", " + smtpClient.UseDefaultCredentials + ", " + smtpClient.Timeout;
sw.WriteLine(errorMsg)
}
catch (Exception ex)
{
string errorMsg = "Cannot send e-mail from " + fromAddress.Address + " to " + originalAddresses[i] + ", " + "Exception: " + ex.Message +
(ex.InnerException != null ? ", " + ex.InnerException.Message : string.Empty);
errorMsg += Environment.NewLine;
errorMsg += smtpClient.Host + ", " + smtpClient.TargetName + ", " + smtpClient.Port + ", " + smtpClient.ClientCertificates + ", " + smtpClient.EnableSsl + ", " + smtpClient.UseDefaultCredentials + ", " + smtpClient.Timeout;
sw.WriteLine(errorMsg);
return false;
}
Any idea of what should I check? Has AccountController something special I should care about? Is the [RequireHttps] controller action attribute somewhat involved?
Thanks.
EDIT1:
Here are our Exchange 2010 settings (please note that we can send the same e-mail message from other ASP.NET MVC controllers):
https://practical365.com/exchange-server/how-to-configure-a-relay-connector-for-exchange-server-2010/
EDIT2:
I was wrong, the problem is not ASP.NET MVC controller related but e-mail address domain related. I discovered that the all the times we include an e-mail address that doesn't belong to our company domain (the outer internet) we get the error above. So now the question is: why the Exchange 2010 Receive Connector is now unable to send e-mail notification to the outer internet?

The server farm changed the outgoing IP address of our server and this was blocking all e-mail messages that contain a recipient not in our company domain. Adding the new outgoing IP address to the Exchange 2010 Receive Connector under Properties->Network->Receive mail from remote servers that have these IP addresses solved the problem.

Related

smtp.office365.com Failure sending mail. Unable to read data from the transport connection: net_io_connectionclosed

I have a support ticket web application, very old, done in ASP.NET webforms
Until 5 October 2021 it has worked perfectly, then has started to miss, sometimes to send out emails.
In the last few days has started to miss sending out most of the emails.
I'm using office365.com as SMTP and POP3 server. POP3 has never given any issue.
I'm using the same account for sending and for reading.
The workload is very very low: I read the POP3 every 5 minutes, and I send out emails just to confirm we have taken in charge the request. And we are talking about 1 email every 1~2 hrs, therefore is not a heavy workload.
This is the code:
private static string sSMTP = "smtp.office365.com";
private static string sPOP3 = "outlook.office365.com";
private static string sEmailAddress = "sender-email#domain.com";
private static string sEmailAccount = "sender-email#domain.com";
private static string sEmailName = "ACME";
private static string sPassword = "SomePassword";
SendMailConfirm("test.user1#gmail.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
SendMailConfirm("test.user2#some-domain.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
SendMailConfirm("test.user2#another-domain.com", "this is a test", "" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"), 1);
private void SendMailConfirm(string sTo, string sSubj, string sBody, int iCallID)
{
SmtpClient client = new SmtpClient(sSMTP);
//authentication
client.Credentials = new System.Net.NetworkCredential(sEmailAccount, sPassword);
client.EnableSsl = true;
client.Port = 587; //tried also 25 with same result.
MailAddress from = new MailAddress(sEmailAddress, sEmailName);
MailAddress to = new MailAddress(sTo);
MailMessage message = new MailMessage(from, to);
message.Subject = sSubj;
message.ReplyTo = new MailAddress("no-reply#domain.com");
message.Body = "Dear user your support ticket has been inserted.\r\n " +
"Request ID: " + iCallID.ToString() + ".\r\n\r\n-----------------\r\n" + sBody;
SendMessage(client, message);
}
private void SendMessage(SmtpClient client, MailMessage message)
{ // here I've tried to add some delay and see what happen but I always get randomly, 90% of the time "Failure sending mail" as exception.
try
{
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 1st message to " + message.To + " succesfully sent!!!!!!!!!!!!!! ";
}
catch (Exception ex)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 1st message to " + message.To + " " + ex.Message + "<hr/>"+ex.StackTrace+"<hr/>";
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " -> retry in 1500ms.";
try
{
Thread.Sleep(1500);
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 2nd message to " + message.To + " succesfully sent!!!!!!!!!! ";
}
catch (Exception ex2)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 2nd message to " + message.To + " " + ex2.Message;
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " ---> retry in 3000ms.";
try
{
Thread.Sleep(3000);
client.Send(message);
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 3rd message to " + message.To + " succesfully sent!!!! ";
}
catch (Exception ex3)
{
output.Text += "<br/>" + DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss") + " 3rd message to " + message.To + " " + ex3.Message;
}
}
}
message.Dispose();
}
The same code works perfectly fine using another email provider, but not on SendGrid or Gmail.
Which could be the cause?
Is there any way to get a more talking message error from SMTP?
After several tries, I've found that the issue is in the System.Net.Mail object of the .Net framework.
I've also found that Microsoft strongly suggest to not use it!:
https://learn.microsoft.com/en-gb/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.8
We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.
After testing it also with SendGrid I've obtained the same behaviour.
Therefore the only solution is to move to MailKit
I've made the code changes, to send the message out with MailKit, and after hundreds of tries, it has never failed.

Set up sender account to my Microsoft.Office.Interop.Outlook._MailItem from my WPF Project

I have a WPF C # project where I have a function to send emails, with Microsoft.Office.Interop.Outlook._MailItem but I don't know how to configure the sender account, it is a gmail account, and I don't know how to tell it or how to give it the username and password of it, can someone guide me?
public void sendEMailThroughOUTLOOK(string PDFAdjunto, string XMLAdjunto, string from, string[] to, string subject, string body, string cc)
{
try
{
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
// Create a new mail item.
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
// add to's
if (to[0] != string.Empty && to[0] != null)
{
oMsg.Recipients.Add(to[0]);
}
if (to[1] != string.Empty && to[1] != null)
{
oMsg.Recipients.Add(to[1]);
}
// Mail body
oMsg.Body = body;
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain;
// Mail attachments
Microsoft.Office.Interop.Outlook.Attachment oAttach1 = oMsg.Attachments.Add(XMLAdjunto);
Microsoft.Office.Interop.Outlook.Attachment oAttach2 = oMsg.Attachments.Add(PDFAdjunto);
// Mail subject
oMsg.Subject = subject;
// Resolve accounts
oMsg.Recipients.ResolveAll();
// Send mail
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
// Clean up.
oMsg = null;
oApp = null;
}
catch (System.Exception e)
{
Mensaje = new wMensaje("Error en envío de Mail", DateTime.Now.ToString()
+ System.Environment.NewLine + subject
+ System.Environment.NewLine + " De: '" + from + "' "
+ System.Environment.NewLine + " Para: '" + to[0] + "', '" + to[1] + "' '"
+ (e.Message.Contains("Operación anulada") ? System.Environment.NewLine + System.Environment.NewLine + "--> Asegúrese de tener ABIERTO su Outlook <--" : "")
+ System.Environment.NewLine + System.Environment.NewLine + " Error: "
+ System.Environment.NewLine + System.Environment.NewLine
+ (e.InnerException == null ? e.Message : e.InnerException.ToString()));
Mensaje.ShowDialog();
}
}
I don't know how to configure the sender account, it is a gmail account, and I don't know how to tell it or how to give it the username and password of it
You can use the MailItem.SendUsingAccount property which returns or sets an Account object that represents the account under which the MailItem is to be sent. The SendUsingAccount property can be used to specify the account that should be used to send the MailItem when the Send method is called. This property returns Null (Nothing in Visual Basic) if the account specified for the MailItem no longer exists.
Note, to be able to set up the SendUsingAccount property it must be configured in the Outlook profile.
You may also consider using the System.Net.Mail namespace, read more about that in the Send email using System.Net.Mail through gmail article.

Skype API Converting FullName to Handle?

I am creating an application to send a mass message. The users are being loaded into a listbox. I am loading it into a listbox so I can choose who to and who not to send messages to. Here is what I have.
foreach (User user in axSkype1.Friends)
{
foreach (String friends in listBox1.SelectedItems)
{
if (richTextBox2.Text.Contains("{username}"))
{
axSkype1.SendMessage(friends, richTextBox2.Text.Replace("{username}", "") + user.FullName + " " + "\n\n" + "" + flatTextBox1.Text + "\n\n" + richTextBox1.Text);
}
else
{
axSkype1.SendMessage(friends, richTextBox2.Text + "\n\n" + flatTextBox1.Text + "\n\n" + richTextBox1.Text);
}
}
}
The part where it says user.FullName is what I am having trouble with. When it sends the message it send the message to the person selected but it sends it for how ever many contacts I have. I just want it to send one but with the users FullName.

How to avoid sending duplicate mail in c#

I have written a code which sends mail to the admin for moderation whenever a user adds a content from front end.....the problem is sometimes the admin gets two mails of same content.
below is my code
MailMessage mail = new MailMessage();
string mailto = ConfigurationManager.AppSettings["adminStoryEmail"].ToString();
mail.To.Add(mailto);
//mail.To.Add("vidyasagar.patil#viraltech.in");
mail.From = new MailAddress(ConfigurationManager.AppSettings["fromEmail"]);
mail.Subject = ConfigurationManager.AppSettings["email_subject"];
if (uploadedpath != "")
{
mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + "<br />" + " Download : " + " http://www.achievewithdell.in/uploads/" + uploadedpath + "<br />";
if (story != "")
{
mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
}
}
else
{
mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + " <br />";
if (story != "")
{
mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
}
}
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["smtp_host"]; //Or Your SMTP Server Address
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtp_userid"], ConfigurationManager.AppSettings["smtp_password"]); //Or your Smtp Email ID and Password
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
You say sometimes the email gets sent twice. This would suggest the code you've given us is fine, the problem probably lies with what calls that code.
One way you could eliminate duplicates is to queue up your mails to be sent, perhaps in a database (storing: to, from, subject, body etc). Then periodically, iterate through mails to be sent, ignoring duplicates and marking sent mails so they don't get sent again.
Failing a refactor to your application like that, as the other poster suggested, get out your debugger and set a breakpoint. Depending on your version of Visual Studio, you could use the Breakpoint Hit Count so you only land at the breakpoint on the 2nd time.
Debug and make sure smtp Send() method is not called twice, put a break point on that line.

Email Body Format Problem

i had a problem in format in email. I want to have a new line..
here's the format in email..
Name: sdds Phone: 343434 Fax: 3434 Email: valencia_arman#yahoo.com Address: dsds Remarks: dsds Giftwrap: Yes Giftwrap Instructions: sdds Details: PEOPLE OF THE BIBLE(SCPOTB-8101-05) 1 x Php 275.00 = Php 275.00 Total: Php275.00
here's my C# code..
mail.Body = "Name: " + newInfo.ContactPerson + Environment.NewLine
+ "Phone: " + newInfo.Phone + Environment.NewLine
+ "Fax: " + newInfo.Fax + Environment.NewLine
+ "Email: " + newInfo.Email + Environment.NewLine
+ "Address: " + newInfo.Address + Environment.NewLine
+ "Remarks: " + newInfo.Notes + Environment.NewLine
+ "Giftwrap: " + rbGiftWrap.SelectedValue + Environment.NewLine
+ "Giftwrap Instructions: " + newInfo.Instructions + Environment.NewLine + Environment.NewLine
+ "Details: " + Environment.NewLine
+ mailDetails;
If you're sending it in HTML, make sure you set the format.
mail.BodyFormat = MailFormat.Html;
And then you can use <br/> should you want to.
UPDATE:
Try this as an alternative:
using System.Net.Mail;
...
MailMessage myMail;
myMail = new MailMessage();
myMail.IsBodyHtml = true;
maybe you can try this...
We create seperate email templates (e.g. EmailTemplate.htm), it includes the message to be sent. You will have no problems for new line in message.
Then this is our Code behind:
private void SendEmail()
{
string emailPath = "../EmailTemplate.htm"; //Define your template path here
string emailBody = string.Empty;
StreamReader sr = new StreamReader(emailPath);
emailBody = sr.ReadToEnd();
sr.Close();
sr.Dispose();
//Send Email; you can refactor this out
MailMessage message = new MailMessage();
MailAddress address = new MailAddress("sender#domain.com", "display name");
message.From = address;
message.To.Add("to#domain.com");
message.Subject = "Your Subject";
message.IsBodyHtml = true; //defines that your email is in Html form
message.Body = emailBody;
//smtp is defined in web.config
SmtpClient smtp = new SmtpClient();
try
{
smtp.Send(message);
}
catch (Exception ex)
{
//catch errors here...
}
}
Did you try "+\n" instead of Environment.NewLine?

Categories

Resources