C# SMTP virtual server doesn't send mail - c#

C# SMTP virtual server doesn't send mail. Here's the code:
public static void SendEmail(string _FromEmail, string _ToEmail, string _Subject, string _EmailBody)
{
// setup email header .
SmtpMail.SmtpServer = "127.0.0.1";
MailMessage _MailMessage = new MailMessage();
_MailMessage.From = _FromEmail;
_MailMessage.To = _ToEmail;
_MailMessage.Subject = _Subject;
_MailMessage.Body = _EmailBody;
try
{
SmtpMail.Send(_MailMessage);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
String str = ex.InnerException.ToString();
}
}

It is an Interop exception because that .NET code is relying on Interop(erability) services, non-managed stuff. The message however is pretty clear, the server is unable to relay because it has been configured to reject relaying of emails.
Many years ago that was not a problem and you could virtually use any public SMTP server to send emails. With the advent of SPAM the whole game changed, now in most servers relaying is disabled and your mail send request is rejected.
What you will need here so that it does not reject your mail, is to authenticate your request (account/user and password on that server). It has to be a valid username & password combination known to that SMTP server. You do that by setting those (out of my head sorry) in the .Credentials property. See also the UseDefaultCredentials property, if you set Credentials you need to make sure UseDefaultCredentials is false.

If the error is this:
550 5.7.1 Unable to relay for ragaei.mahmoud#invensys.com
Then your SMTP server cannot send to that email address. Use a different SMTP server or configure it to relay out to the internet. The local one will probably only send to addresses on your own domain. If this is an SMTP server configuration question, you may have more luck asking on Superuser.

Related

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.

Sending email through SMTP fails : MailBox name not allowed

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.

Mail sent in spam

I have made asp.net webservice in C# to send mail on given mailid as parameter.
Mail is sent but it is shown as spam, not as an inbox mail.
I have used following code;
.NET CODE :
public int SendMail(string mailto, string username, string password)
{
try
{
string mailFrom = "test#gmail.com";
string siteName = "www.XYZ.com";
MailAddress fromAddress = new MailAddress(mailFrom, siteName);
SmtpClient mailClient = new SmtpClient();
MailMessage message = new MailMessage();
message.From = fromAddress;
message.To.Add(mailto);
message.Subject = "Your User Name and Password";
message.IsBodyHtml = true;
mailClient.Host = "relay-hosting.secureserver.net";
mailClient.UseDefaultCredentials = false;
mailClient.EnableSsl = false;
string body = "<HTML><BODY><CENTER><H2>Your User Name :'" + username + "' </H2><BR/><H2>Your Password :'" + password + "' </H2></CENTER></BODY></HTML>";
message.Body = body;
mailClient.Send(message);
return 1;
}
catch (Exception ex)
{
return 0;
}
}
WEB.CONFIG CODE :
<system.net>
<mailSettings>
<smtp from="test#gmail.com">
<network host="relay-hosting.secureserver.net" />
</smtp>
</mailSettings>
</system.net>
What can be the problem ?
Thank you..
The content of your MailMessage is being identified as spam by the recipient's provider or the relay server you're using is blacklisted. If you are using relay-hosting.secureserver.net the later is probably the case. I would suggest using a more trusted relay provider than GoDaddy.
Your FROM address is GMAIL.COM and you are NOT sending email from GMAIL server but from another server. Using DomainKeys Identified Mail (DKIM) and Sender Policy Framework (SPF) it is now possible (and most sysadmins do) specify authorized email sending servers for that domain in the domain's DNS records. This way, when a email recipient server receives an email, it can check for authenticity of the source of the email by checking the email sending server with the list of servers mentioned as authorized in the sender domain's DNS. If it does not match, then as per rules set or specified by the sender domain's sysadmin in their DNS record, the email may be outright rejected or saved as spam in the spam folder.
I guess this is what is happening. You should also check the sending server (SMTP) credentials using http://www.mxtoolbox.com/blacklists.aspx service before sending emails.
The email will likely show up as spam if you send from an IP address that does not have a valid SPF record for the domain you are claiming it is coming from. In this example ""relay-hosting.secureserver.net" does not have a valid IP address to act as an SMTP server for gmail.
Try doing a test sending from the actual domain you will be using in real life instead of "test#gmail.com".
If it still gets marked as spam it is very easy to add an SPF record for test#youractualdomain.com. Here is a site that has helped me in the past: http://www.zytrax.com/books/dns/ch9/spf.html
There are several things at play that conspire to raise the spam score of your email. Remember that it's not spam/notspam, but rather a "spam score" above which your email will be marked as spam by the receiving server.
I would guess that the factors at play in your case are the folowing:
HTML body with no alternative text message
From address does not correspond to actual server mail is sent from
From address does not exist
SMTP server (relay-hosting.secureserver.net) has a low reputation
No SPF or domainKey records
The solution is in several points as well:
Create an alternate text version of your message and include it in the body (this answer explains how to do that)
Use a From address that actually exists on the server the email is sent from
Use a reputable provider for your SMTP server, such as Sendgrid, postmarkApp or Mailjet
Specifying SPF and DomainKeys DNS records allows the receiving server to identify your message as coming from the right server
Good luck!

Permission error when sending e-mail using my SMTP server in IIS7

I just recently bought my own server with IIS7, and I'm trying to set up SMTP so that I can send an e-mail from my website.
Here's my smtp settings:
Here is my code that sends the e-mail:
private static void SendEmail(IEnumerable<MailAddress> to,
IEnumerable<MailAddress> bcc, MailAddress from,
string subject, string bodyHtml)
{
var mail = new MailMessage { From = from, Subject = subject,
Body = bodyHtml, IsBodyHtml = true };
foreach (var address in to)
{
mail.To.Add(address);
}
foreach (var address in bcc)
{
mail.Bcc.Add(address);
}
try
{
string server = ConfigurationManager.AppSettings["SMTPServer"];
int port = Int32.Parse(ConfigurationManager.AppSettings["SMTPPort"]);
var smtp = new SmtpClient
{
Host = server,
Port = port
};
smtp.Send(mail);
}
catch (Exception err)
{
}
}
And my config settings:
<add key="SMTPServer" value="localhost" />
<add key="SMTPPort" value="25" />
I get an error at smtp.Send(mail); that says:
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.
Well, I have no authentication requirements on my smtp server, it says so in my settings in the screenshot.
I looked around, and other people had this problem if they were sending the e-mail from a different e-mail specified in their settings, but I'm sending mine from info#mysite.com. I am sending it to an #gmail.com account though, so it is sending to a non-local e-mail address.
What am I doing wrong here?
I wanted to add the answer to this for others searching
Make sure SMTP is up and running and no errors are being thrown. Here is a reference that might help.
http://forums.iis.net/p/1157046/1901343.aspx
I met more than 2 people when I wanted to send.
I'm just sending it to 2 people.
My problem is solved.

C# send email using implicit ssl

Is there any library preferable free that can be used in order to sens email using implicit ssl protocol. My hosting provider support ssl emails ... but standard .net email client cannot handle that.
Use the TLS port (ie 587) rather than the SSL port. I had the same issue for months until I found this solution.
Sending email in .NET through Gmail
System.Net.Mail does support "explicit SSL" (also known as "StartTLS" - usually on port 25 or 587), but not "implicit SSL" (aka "SMTPS" - usually on port 465).
As far as I know, explicit SSL starts from an unsecured connection, then the STARTTLS command is given and finally a SSL secured connection is made.
Implicit SSL, on the other side, requires that the SSL connection is set up before the two parties start talking.
Some servers (like gmail) accept both, so you simply need to set EnableSsl to true and send to the right port. If your server does not support explict SSL, though, this "simple way" is not an option.
I'm also still looking around for a general solution for using System.Net.Mail with implicit SSL, with no luck so far.
Anyway take a look at this article, it may give you some insight.
[edit: #Nikita is right, fixed port numbers to avoid confusion]
You may still be able to use the deprecated System.Web.Mail.MailMessage API (and set its "http://schemas.microsoft.com/cdo/configuration/smtpusessl" option, for explicit SSL/TLS):
System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage();
// ...
mailMsg.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
true);
Alternatively, if you can, you could run something like stunnel locally to establish an SSL/TLS tunnel from your localhost to your SMTP server. Then, you would have to connect normally (without SSL/TLS) to the tunnel's localhost end as your SMTP server.
Try to check AIM (Aegis Implicit Mail) on https://sourceforge.net/p/netimplicitssl/wiki/Home/
As one of options, our SecureBlackbox includes SMTP component which works via both implicit and explicit SSL and supports different authentication mechanisms (including SASL, NTLM etc).
AspNetEmail supports Explicit SSL and Implicit ssl
http://www.advancedintellect.com/download.aspx
You can use AIM (Aegis Implicit Mail) to send email through implicit SSL:
First install the package: Install-Package AIM
Then Use the sample code to send email
class Mail
{
private static string mailAddress = "{you email address}";
private static string host = "{your host server}";
private static string userName = "{your user name}";
private static string password = "{your password}";
private static string userTo = "{to address}";
private static void SendEmail(string subject, string message)
{
//Generate Message
var mailMessage = new MimeMailMessage();
mailMessage.From = new MimeMailAddress(mailAddress);
mailMessage.To.Add(userTo);
mailMessage.Subject = subject;
mailMessage.Body = message;
//Create Smtp Client
var mailer = new MimeMailer(host, 465);
mailer.User = userName;
mailer.Password = password;
mailer.SslType = SslMode.Ssl;
mailer.AuthenticationMode = AuthenticationType.Base64;
//Set a delegate function for call back
mailer.SendCompleted += compEvent;
mailer.SendMailAsync(mailMessage);
}
//Call back function
private static void compEvent(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState != null)
Console.Out.WriteLine(e.UserState.ToString());
Console.Out.WriteLine("is it canceled? " + e.Cancelled);
if (e.Error != null)
Console.Out.WriteLine("Error : " + e.Error.Message);
}
}

Categories