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.
Related
i try to send an email with this code...but i have this error :"Client was not authenticated to send anonymous mail during MAIL FROM"
code:
var smtpClient = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 25, //587
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod= System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential("{mail}", "{password}","{domain}");
var message = new MailMessage
{
From = new MailAddress("{mail}","{display name}",System.Text.Encoding.UTF8),
Subject = "Test mail",
IsBodyHtml = false
};
message.To.Add("{mail}");
message.Body = "This is a test mail. ";
try{
smtpClient.Send(message);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
thanks
This indicates that you are connecting to the SMTP client submission endpoint (smtp.office365.com), which can't be used for direct send. For direct send, use the MX endpoint for your Office 365 tenant, which ends with "mail.protection.outlook.com." So, please let your admin check the MX record. Moreover, please check if the SMTP port is 25/TLS.
Moreover, you can try the following suggestions to check if there is any improvement:
Remove the account and add it again to check the issue.
Try using another same tenant account to check the issue.
See Client was not authenticated to send anonymous mail for more information.
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've written several programs that send email from C#. This works great in winXP, but I find it breaks in Win7. My understanding is that even though the SMTP server I'm referencing is on another computer, the sending computer needs to have the SMTP service installed (and win7 does not).
I know its possible to install a third party SMTP server, but then I'd need to do that on every computer running my programs. Instead, I'd like to include a temporary SMTP server in my project that I can use entirely from code to do the same job. Does anyone know of a library (or sample code) on how I can include a temporary SMTP server in my project?
Here is my code:
public static void sendEmail(String[] recipients, String sender, String subject, String body, String[] attachments)
{
MailMessage message;
try
{
message = new MailMessage(sender, recipients[0]);
}
catch (Exception)
{
return;
}
foreach (String s in recipients)
{
if (!message.To.Contains(new MailAddress(s)))
message.To.Add(s);
}
message.From = new MailAddress(sender);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("PRIVATE.PRIVATE.PRIVATE", 25);
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = true;
if (attachments.Length > 0)
{
foreach (String a in attachments)
{
message.Attachments.Add(new Attachment(a));
}
}
try
{
smtp.SendAsync(message, null);
To send emails from c#, you do not need a local SMTP service. You just need the System.Net.Mail library. Using a remote SMTP server (possibly one with valid PTR settings and not one in your network to avoid being regarded as a spammer) should definitely suffice.
It may be a credentials issue. Change SendAsync to Send to see if you are getting any exceptions. Or add a handler for the Async invocation
smtp.SendCompleted += delegate(object s, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
};
Following changes to your code works for me in Win7
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(GoogleUserEmail, GooglePassword);
smtp.EnableSsl = true;
// smtp.UseDefaultCredentials = true;
if (attachments != null && attachments.Length > 0)
{
foreach (String a in attachments)
{
message.Attachments.Add(new Attachment(a));
}
}
try
{
smtp.Send(message);
}
I have never found an embeddable SMTP server, but both of these are close and you could probably modify them to fit your needs.
http://www.codeproject.com/KB/IP/smtppop3mailserver.aspx
http://www.ericdaugherty.com/dev/cses/developers.html
I'm going to keep looking because this is also something I'd find useful. I'll post more if I find any.
If you just use an unconfigured service to send your emails you will definitely end up in the SPAM folder due to reverse DNS and SPF checks failing. So you'll want to configure your server properly. Alternatively you can use a 3rd party service like Elastic Email. Here is Elastic Email's sample code which uses HTTP to send the mail:
public static string SendEmail(string to, string subject, string bodyText, string bodyHtml, string from, string fromName)
{
WebClient client = new WebClient();
NameValueCollection values = new NameValueCollection();
values.Add("username", USERNAME);
values.Add("api_key", API_KEY);
values.Add("from", from);
values.Add("from_name", fromName);
values.Add("subject", subject);
if (bodyHtml != null)
values.Add("body_html", bodyHtml);
if (bodyText != null)
values.Add("body_text", bodyText);
values.Add("to", to);
byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
return Encoding.UTF8.GetString(response);
}
Have you tried specifying SMTP settings in an App.config file? Something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<specifiedPickupDirectory pickupDirectoryLocation="C:\tmp"/>
<network host="smtp.example.com"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
If you change deliveryMethod="SpecifiedPickupDirectory" then it'll just write a file representing the email that would be sent to the directory you specify.
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.
I have code,
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(oMailMessage);
(all variables have values)
I have installed SMTP virtual services. why it is unable to send emails. why it is not working ??
EDIT
public bool SendMail(string strToEmailId, string strFromEmaild, string strSubject, string strBody)
{
try
{
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "SERVERNAME";
SmtpMail.Send(oMailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
I have this code. It is executing fine and is returning true, but I'm not getting any email in the inbox.
What else could be wrong?
Getting some mails in BadMail Dir at C:\Inetpub\mailroot\Badmail also in Queue Directory getting some mails here ... what does that means..??
I found that mail only can sent to gmail accounts... why it is?
As mentioned by others, your code is fine and is most likely something in your SMTP configuration or maybe your email client your sending your test emails to is marking them as spam. If it's spam, well that's easy enoughto figure out.
If it's something with the email, you can go to your mailroot folder and their will be some folders there with the email files along with a description. See if there's anything in the BadMail folder or the queue folder and open them up in notepad and view what error is given for why they weren't sent.
Determine what the error is:
try
{
SmtpMail.Send(oMailMessage);
}
catch (Exception ex)
{
//breakpoint here to determine what the error is:
Console.WriteLine(ex.Message);
}
From here, please edit your question with that exception details.
Its hard to tell, but one possibility is that you haven't enabled anonymous access on the SMTP virtual server. Go to the the virtual server properties dialog, select the Access tab, click the Access Control button, and make sure that Anonymous Access is enabled.
There doesn't appear to be anything functionally wrong with your program. It's likely a configuration issue between your program and the mail server. I would try the following to diagnose the problem.
Wrap the code in a try/catch block and see if the exception message contains useful data
Use 127.0.0.1 instead of localhost just to rule out anything crazy
Ensure your SMTP server is running on the standard port (25 I believe)
Hello you can follow the following code:
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("your gmail id", "password");
MailMessage msg = new MailMessage();
msg.To.Add(textBoxTo.Text);
msg.From = new MailAddress("your gmail id");
msg.Subject = textBoxSubject.Text;
msg.Body = textBoxMsg.Text;
Attachment data = new Attachment(textBoxAttachment.Text);
msg.Attachments.Add(data);
client.Send(msg);
MessageBox.Show("Successfully Sent Message.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
have you tried 127.0.0.1 instead of Localhost?
Also have you tested that the SMTP service is working, check out this link for details.
In the virtual smtp server Add relay restrictions and connection control so that none of the outside connections are allowed