**It just says " Failure sending mail."
Not sure its the problem with the code or SMTP server ? Please help here is my code, the variables are send through a form and i have confirmed that all variables are ok
SMTP Settings is in Web.config**
<?xml version="1.0"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="newsletter#abc.com">
<network host="mail.abc.com" port="25" userName="newsletter#abc.com" password="abc#!#"/>
</smtp>
</mailSettings>
</system.net>
<system.web>
</system.web>
</configuration>
Code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdSend_Click(object sender, EventArgs e)
{
MailMessage mMailMessage = new MailMessage();
// address of sender
mMailMessage.From = new MailAddress(txtFrom.Text);
// recipient address
mMailMessage.To.Add(new MailAddress(txtTo.Text));
// Check if the bcc value is empty
if (txtBcc.Text != string.Empty)
{
// Set the Bcc address of the mail message
mMailMessage.Bcc.Add(new MailAddress(txtBcc.Text));
}
// Check if the cc value is empty
if (txtCc.Text != string.Empty)
{
// Set the CC address of the mail message
mMailMessage.CC.Add(new MailAddress(txtCc.Text));
} // Set the subject of the mail message
mMailMessage.Subject = txtSubject.Text;
// Set the body of the mail message
mMailMessage.Body = txtBody.Text;
// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal;
// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient();
// Send the mail message
try
{
mSmtpClient.Send(mMailMessage);
}
catch (Exception ex)
{
;//log error
lblMessage.Text = ex.Message;
}
finally
{
mMailMessage.Dispose();
}
}
}
Try using a telnet command to check if you can send a mail.
Start-> type "telnet":
open smtp.server.com 25
Helo smtp.server.com
Mail from:yourAdress#server.com
Rcpt to:yourAdress#server.com
Data
Subject:The life
OMG
.
Quit
If telnet isn't there, add it through add/remove windows features. See :http://technet.microsoft.com/en-us/library/cc771275(v=ws.10).aspx
First, we didn't the specify the SMTP server name:
SmtpClient smtp = new SmtpClient(#"abc.company.com");
Second, after specifying the SMTP server name like the snippet above, Make sure the firewall or Symantec (or some program like that) is not blocking the outbound request.
In your try catch block, you will need to go through all the exceptions. Keep looping until exception.innerexception is null. A more detailed error message will be found in the inner exception to why the mail message failed to be sent. The outer exception and corresponding message will be generic and not that useful.
Some samples can be found here:
Best way to check for inner exception?
Here some Psuedo Code
while (ex != null)
{
//LogThisException(ex);
ex = ex.InnerException;
}
Related
I have created one webpage in ASP.net with C#. In which I have put one button when this button clicks need to send mail. But, when I click on this button getting this exception :-
System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.7.1 : Relay access denied at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button1_Click(Object sender, EventArgs e) in c:\Users\jay.desai\Documents\Visual Studio 2013\WebSites\WebSite2\Default.aspx.cs:line 47
Please refer below code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("serveradmin.dmd#ril.com");
mail.Subject = "Pallet Shortage Emergency";
mail.To.Add("jay.desai#ril.com");
mail.Body ="Only 100 pallets are availabe in ASRS. This is system generated mail do not reply";
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
System.Net.NetworkCredential("serveradmin.dmd#ril.com", "1234");
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
The server error is indicating that it will not relay messages. Usually this means that you need to authenticate with the server before it will allow you to send email, or that it will only accept emails for delivery from specific source domains.
If you are always going to be sending to a single email domain then you can generally use the registered MX server for the domain. In this case (ril.com) the MX server list includes several primary mail servers, but the first one for me is: gwhydsmtp010.ril.com. I'd try that as the target mail server if your website is hosted outside the network that the mail server is on.
Alternatively you can provide SMTP login credentials to the SmtpClient object like this:
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("username", "password");
Logging in to the server will generally solve most 5.7.1 errors.
One final method that might be useful if you have admin rights on the Exchange server is to setup an SMTP connector to allow relay from a specific source address (your web server). I wouldn't recommend this however as any open relay is a Bad Idea(tm).
I am using visual studio 2010. When i run the asp page it shows the errors "The name 'txtname' doest not exists in the current context". I am new in C# programming needs help.
I am using all the defined variables but i am still confused why it is giving errors.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
namespace WebApplication1
{
public partial class contactus : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("myinfo#yahoo.com");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("abc#gmail.com");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = txtName.Text + " : " + txtName1.Text;
msg.Body = txtMessage.Text;
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("abc#gmail.com", "paswword");
client.Credentials = credentials;
//Send the msg
client.Send(msg);
//Display some feedback to the user to let them know it was sent
lblResult.Text = "Your email has been received, you will be contacted soon by our representative if required.";
//Clear the form
txtName.Text = "";
txtName1.Text = "";
txtMessage.Text = "";
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again.";
}
}
}
}
When .cs file name in Code behind attribute does not match , then only this kind of error can occur.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Or it seems that you have copy and pasted the control or code related to it.
This often creates problem in designer file.
You can delete that textbox and once again drag-drop it on your app from toolbar
add runat="server" in the txtName control if it is a regular html control.
I know this is and old question. I got the same problem after copying few divs in a seperate place. This might be useful to anyone in future. Just remove runat="server" attribute of the relevenat tag and again insert it. It worked for me 100%.
I am trying to implement a "forgot password" method into my site. It works perfectly in debug. Using the same code and db, but published to our web server it fails when it tries to send the message.
The error that I get is:
There was an error sending you an email.
The specified string is not in the form required for an e-mail address.
The email is valid, so I have no idea why it is failing.
Because it is a live environment I cannot step through the code to see exactly where and why it is failing. I implemented db logging so I can see how far it gets before it fails and it successfully executes all code up to this point:
var smtp = new SmtpClient
{
Host = host,
Port = port,
EnableSsl = ssl,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPw)
};
using (var message = new MailMessage()
{
Subject = subject,
Body = body,
IsBodyHtml = ishtml,
From = fromAddress
})
{
foreach (MailAddress t in toCol)
{ message.To.Add(t); }
foreach (MailAddress c in ccCol)
{ message.CC.Add(c); }
foreach (MailAddress b in bccCol)
{ message.Bcc.Add(b); }
smtp.Send(message);
}
It never gets to the next db logging so it has to be failing here. In my test I have exactly one email address for the to and none for bcc and cc. When stepping through in debug it correctly loads the single email address and doesn't load any for cc and bcc. I have no idea what it is considering to be an invalid email address.
EDIT:
We use Google Apps as our mail server so both my workstation and the server have to connect. I am using the following:
Host: smtp.gmail.com
Port: 587
EnableSsl: true
Credentials: valid username and password that work in debug
EDIT 2:
To incorporate some of the suggestions from you.
The fromAddress is set earlier using values from the db like this:
DataTable ts = DAL.Notification.GetNotificationSettings();
var fromEmail = ts.Rows[0]["fromadr"].ToString().Trim();
var fromName = ts.Rows[0]["fromname"].ToString().Trim();
var host = ts.Rows[0]["server"].ToString().Trim();
var port = Convert.ToInt32(ts.Rows[0]["smtpport"]);
var ssl = Convert.ToBoolean(ts.Rows[0]["is_ssl"]);
var ishtml = Convert.ToBoolean(ts.Rows[0]["is_html"]);
var bodyTemplate = ts.Rows[0]["bodyTemplate"].ToString();
body = bodyTemplate.Replace("{CONTENT}", body).Replace("{emailFooter}","");// Needs to use the Global emailFooter resource string
var fromAddress = new MailAddress(fromEmail, fromName);
I have even tried hard coding the from address like this:
message.From = new MailAddress("websystem#mydomain.com");
I still get the error and it still fails when defining the message.
Any other suggestions on how to find and fix the problem?
ANSWER
I did not define the default from address in the web.config like this:
<system.net>
<mailSettings>
<smtp from="email#yourdomain.com">
<network host="smtp.yourdomain.com"/>
</smtp>
</mailSettings> </system.net>
So it failed at var message = new MailMessage() before I could define the correct from address.
I either needed to implement var message = new MailMessage(From,To) or provide a default from address in web.config (which is what I did)
This error can be caused by two things:
One of the email addresses your using (for message.To, message.CC or message.Bcc) is invalid, i.e. it doesn't follow the required format of someuser#somedomain.xxx.
The From address configured in Web.Config is invalid:
<system.net>
<mailSettings>
<smtp from="invalid##email">
<network host="smtp.gmail.com"/>
</smtp>
</mailSettings>
</system.net>
My recommendation is to use try/catch statements to further narrow the problem. I'd also temporarily lose the using statement for the MailMessage for easier troubleshooting.
Example:
var smtp;
try
{
smtp = new SmtpClient
{
Host = host,
Port = port,
EnableSsl = ssl,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPw)
};
}
catch (Exception exc)
{
MessageBox.Show("Error creating SMTP client: " + exc.Message);
}
var message = new MailMessage();
try
{
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = ishtml;
message.From = fromAddress;
}
catch (Exception exc)
{
MessageBox.Show("Error creating MailMessage: " + exc.Message);
}
try
{
foreach (MailAddress t in toCol)
message.To.Add(t);
}
catch (Exception exc)
{
MessageBox.Show("Error adding TO addresses: " + exc.Message);
}
try
{
foreach (MailAddress c in ccCol)
message.CC.Add(c);
}
catch (Exception exc)
{
MessageBox.Show("Error adding CC addresses: " + exc.Message);
}
try
{
foreach (MailAddress b in bccCol)
message.Bcc.Add(b);
}
catch (Exception exc)
{
MessageBox.Show("Error adding BCC addresses: " + exc.Message);
}
try
{
smtp.Send(message);
}
catch (Exception exc)
{
MessageBox.Show("Error sending message: " + exc.Message);
}
Alternatively, you could replace the various MessageBox.Show() statements with something that writes to a log file. By breaking this up you should be able to pinpoint the problem with more accuracy.
I am having an error that is occurring sporadically. When I encounter this error, if I try again, the e-mail will send. I cannot reliably reproduce the error, but it is hapening frequently enough to be a problem.
System.Net.Mail.SmtpException : Service not available, closing transmission channel. The server response was: [Servername]: SMTP command timeout - closing connection
Stack Trace:
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) 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)
Here's the code in question. It uses an HTML template (database driven with a web url default backup) to inject values and create an html e-mail.
public void AccountActivationEmail(Common.Request.Email.AccountActivation request)
{
var profile = profileRepository.GetOne(new ProfileByUsername(request.Username, request.SiteId));
var options = siteService.GetOptions(new GatewayOptionsRequest()
{
SiteId = request.SiteId
});
var site = options.Site;
ExpiringHMAC hmac = new ExpiringHMAC(request.ExpireOn, new string[] { request.AccountId.ToString(), request.AccountKey.ToString(), request.Username });
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("{{logourl}}", String.IsNullOrEmpty(options.FullyHostedGateway.LogoUrl) ? UrlHelper.ConvertRelativeToAbsolute("/content/images/spacer.png") : options.FullyHostedGateway.LogoUrl);
data.Add("{{name}}", profile.Name.DisplayName);
data.Add("{{sitename}}", site.Name.DisplayName);
data.Add("{{activationlink}}", String.Format(ActivationUrlFormat, options.UrlFriendlyName, Encryption.EncryptQueryString(request.Username), hmac.ToString()));
MailDefinition template = new MailDefinition();
MailMessage message = null;
var emailTemplate = options.GetEmailTemplate(EmailTemplateType.ActivateAccount);
string defaultSubject = "Activate Account";
bool hasTemplate = false;
if (emailTemplate != null)
{
hasTemplate = !String.IsNullOrEmpty(emailTemplate.Template);
}
if (!hasTemplate)
{
template.BodyFileName = activationDefaultTemplateUrl;
message = template.CreateMailMessage(request.EmailAddress, data, new System.Web.UI.LiteralControl());
message.IsBodyHtml = true;
message.Subject = defaultSubject;
}
else
{
message = template.CreateMailMessage(request.EmailAddress, data, emailTemplate.Template, new System.Web.UI.LiteralControl());
message.IsBodyHtml = emailTemplate.IsHtml;
if (!String.IsNullOrEmpty(emailTemplate.Subject))
message.Subject = emailTemplate.Subject;
else
message.Subject = defaultSubject;
}
if (options.ContactDetails != null)
{
if (!String.IsNullOrEmpty(options.ContactDetails.EmailAddress))
message.From = new MailAddress(options.ContactDetails.EmailAddress);
}
SmtpClient client = new SmtpClient();
client.Send(message);
}
This code is part of a class that is generated as a singleton using Structuremap. I thought maybe that might be causing the issue, but every time the method is called, a new SmtpClient object is created, which should eliminate the problems I have seen about using the same connection to send multiple e-mails.
We have nothing blocking or restricting the connection, which is the official stance our e-mail hosting is taking on this issue. I want to see if there's any way to do this better so I don't get these errors.
EDIT:
I do have my mail server defined in my web.config. I have confirmed with my e-mail hosting that my settings are correct.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="no-reply#mydomain.com">
<network host="smtp.emailhost.com" userName="someaddress#mydomain.com"
password="myPassword1" port="2500" />
</smtp>
</mailSettings>
</system.net>
Are you disposing of the Smtp Client object after sending? From http://connect.microsoft.com/VisualStudio/feedback/details/337557/smtpclient-does-not-close-session-after-sending-message it would appear that "...even if you are creating a new instance of the SmtpClient every time, it still uses the same unerlying session."
So perhaps
using (SmtpClient client = new SmtpClient())
{
client.Send(message);
}
I have used this code to send mails but I am not getting any error but I'm able to receive the mail. The default smtp server is also set to "127.0.0.1" as my local host in relay mail in the "inetmgr" but I'm still not able to receive the mail. I don't know where the problem is.
In emailsender.cs class this is the code:
public void SendEmail(string To, String Subject, String Body, String uname)
{
string body = "Hi " + uname + ",\n\n \t" + Body + "\n" + " \n Regards, \n LMS Team" + "\n\n\tSent at: " + DateTime.Now + " \n\n\t\t---- This is an auto generated mail. Please do not reply.";
try
{
try
{
MailMessage Message = new MailMessage();
Message.From = new MailAddress("karhik.varadarajan#asteor.com");
if (!string.IsNullOrEmpty(To))
Message.To.Add(new MailAddress(To));
Message.Subject = Subject;
Message.Body = body;
try
{
SmtpClient smtpClient = new SmtpClient("localhost");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Port = 25;
smtpClient.UseDefaultCredentials = false;
smtpClient.Send(Message);
}
catch (System.Web.HttpException ehttp)
{
throw new Exception("Email Sending Failed", ehttp);
}
}
catch (IndexOutOfRangeException ex)
{
throw new IndexOutOfRangeException("Email Sending Failed", ex);
}
}
catch (System.Exception ex)
{
throw new Exception("Email Sending Failed", ex);
}
}
In the .aspx file:
protected void Page_Load(object sender, EventArgs e)
{
EmailSender email = new EmailSender();
email.SendEmail("karhik.varadarajan#asteor.com", "testingmail", "this is a test mail", "From");
}
If you use PickupDirectoryFromIis option, Check you C:\Inetpub\mailroot\Pickup or Queue or Badmail directory whether the EML file created or not. If it is in PickUp or Queue folder, IIS may process the file. If it is in BadMail, IIS unable to process the file.
I experienced the same issue,sometimes the organization wont allow access to send email.so i tried email relaying server. try elastic email.
If there are no error there are most likely an smpt server setup problem. Firstly, you are using localhost, not 127.0.0.1. I would recommend as a best practice to use 127.0.0.1 when calling localhost.
Even if it is a "shouldn't need too" there are no reason at all, using localhost. At least put "127.0.0.1 localhost" in windows etc\hosts file. You may also try a external SMTP host that you know ou have access to (like your isp). I know misconfigured smtp hosts CAN appear as the was sended succesfully.
However, as other already stated above, there can be a lot of other problems like access to send mail. Though, i think most errors like those will throw an error back to you.