Email sending error in ASP.NET using C# - c#

This is the code for email sending, but it gives error in try block:
protected void Page_Load(object sender, EventArgs e)
{
EmailUtility email = new EmailUtility();
email.Email = new MailMessage();
string body = email.GetEmailTemplate(Server.MapPath("~/EmailTemplates"), "test.htm");
EmailMessageToken token = new EmailMessageToken();
token.TokenName = "$Name$";
token.TokenValue = "Ricky";
EmailMessageTokens tokens = new EmailMessageTokens();
tokens.Add(token);
//av.LinkedResources.Add(lr);
email.Email.Body = email.ReplaceTokens(body, tokens);
email.Email.To.Add(new MailAddress("sahil4659#gmail.com"));
email.Email.IsBodyHtml = true;
email.Email.From = new MailAddress("sahil4659#gmail.com");
email.Email.Subject = "Hello from bootcamp";
email.SMTP.Host = ConfigurationManager.AppSettings["SMTPServer"];
try
{
email.SMTP.Send(email.Email);
Response.Write("Email sent !");
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
The error is:
at System.Net.Mail.IisPickupDirectory.GetPickupDirectory()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at _Default.Page_Load(Object sender, EventArgs e) in c:\Users\Sahil\Desktop\Csharp Email Code(2)\Test website\EmailTest.aspx.cs:line 38

I'm going to read your mind and assume that you're seeing System.Net.Mail.SmtpException: Cannot get IIS pickup directory. Googling around, I see references to SMTP configuration you'll need in your web configuration. Your mail server may require credentials, so you might need something like this:
<system.net>
<mailSettings>
<smtp from="fromaddress">
<network defaultCredentials="true"
host="smtpservername" port="smtpserverport"
userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
... in your web.config. Essentially, configure your web app to be able to talk with the SMTP server.
See this thread for more reference, and here's relevant MSDN documentation.

Related

Sending email via Gmail SMTP hangs indefinitely without error

In my ASP.NET MVC 5 application, I use emails (System.Net.Mail) primarily for account authentication. It's worked perfectly until recently, and I have no idea what happened. I didn't change anything even slightly related to emails, as far as I know.
When I try to step into the SendAsync call in the controller, it transfers control back to the browser where it hangs indefinitely. Eventually I have to stop and restart the application pool just to access any page, which takes a couple minutes (usually it can be turned back on almost instantly).
I have it set up to use a Google app password, which is a requirement (you get an error about security otherwise). It doesn't seem to even get as far as Google, since the new app password hasn't been used.
I've tried the TLS port as well as the SSL port. Last time I got it working was using TLS.
Web.config:
<configuration>
<appSettings>
<add key="SmtpUsername" value="email#gmail.com" />
<add key="SmtpPassword" value="AppPassword" />
<add key="SmtpSender" value="email#gmail.com" />
<add key="SmtpHost" value="smtp.gmail.com" />
<add key="SmtpPort" value="587" /> <!-- SSL: 465, TLS: 587 -->
<add key="SmtpEnableSsl" value="true" />
</appSettings>
</configuration>
Email code:
public class EmailClient : SmtpClient
{
public EmailClient()
{
UseDefaultCredentials = false;
Host = WebConfigurationManager.AppSettings.Get("SmtpHost");
Port = int.Parse(WebConfigurationManager.AppSettings.Get("SmtpPort"));
EnableSsl = bool.Parse(WebConfigurationManager.AppSettings.Get("SmtpEnableSsl"));
Credentials = new NetworkCredential(WebConfigurationManager.AppSettings.Get("SmtpUsername"),
WebConfigurationManager.AppSettings.Get("SmtpPassword"));
DeliveryMethod = SmtpDeliveryMethod.Network;
Timeout = 30000; // Waiting 30 seconds doesn't even end the "loading" status
}
}
public class EmailMessage : MailMessage
{
private bool isBodyHtml = true;
public EmailMessage(string subject, string body, string recipients)
: base(WebConfigurationManager.AppSettings.Get("SmtpSender"), recipients, subject, body)
{
IsBodyHtml = isBodyHtml;
}
public EmailMessage(string subject, string body, IEnumerable<string> recipients)
: base(WebConfigurationManager.AppSettings.Get("SmtpSender"), string.Join(",", recipients), subject, body)
{
IsBodyHtml = isBodyHtml;
}
}
public static class Email
{
/// <param name="recipients">Comma-delimited list of email addresses</param>
public static async Task SendAsync(string subject, string body, string recipients)
{
using (EmailMessage msg = new EmailMessage(subject, body, recipients))
using (EmailClient client = new EmailClient())
{
await client.SendMailAsync(msg);
}
}
/// <param name="recipients">Collection of email addresses</param>
public static async Task SendAsync(string subject, string body, IEnumerable<string> recipients)
{
using (EmailMessage msg = new EmailMessage(subject, body, recipients))
using (EmailClient client = new EmailClient())
{
await client.SendMailAsync(msg);
}
}
}
Usage:
public class TestController : BaseController
{
public async Task<ActionResult> Test()
{
await Email.SendAsync("TEST", "test", "anaddress#gmail.com");
return View(); // Never reaches this point
}
}
OP here. As some answers allude, there was nothing wrong with my code. I'm not sure which of the below I had changed without retesting, but this is what you must have to use Gmail SMTP:
Use TLS port 587
Set SmtpClient.EnableSsl to true
Enable MFA for the Google account and use an app password for the SmtpClient.Credentials. I needed to enable MFA to create an app password.
Please note the Documentation and see the Gmail sending limits. under Gmail SMTP server section.
Your code looks fine, the only thing I see is that you are enabling SSL, but using the port distained for 'TLS' so users who will use the SSL method, will engage in an issue.
Beside from that, nothing appears to the eye.
There is standard way to send emails from ASP.NET.
web.config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" password="password" port="587" userName="user#gmail.com"/>
</smtp>
</mailSettings>
</system.net>
.cs
var smtp = new SmtpClient(); // no other code.
var msg = CreateEmailMessage();
//I use try... catch
try{
smtp.Send(msg);
//return true; //if it is a separate function
}
catch(Exception ex){
//return false;
//use ex.Message (or deeper) to send extra information
}
Note that Gmail doesn't except a sender other than username. If you want your addressee to answer to another address then use
msg.ReplyToList.Add(new MailAddress(email, publicName));

Code runs fine on localhost but doesn't execute on gatorhost

I wrote a small website in VWD. I am running it on my home machine using the localhost features of VWD. It runs flawlessly.
Now the backstory. I had a linux server with gatorhost. I had them switch my domain and my server type to windows because i decided to learn asp.net(c#). I had a million problems with them hours on the phone. Issues with unable to connect when you search for my domain and my e-mail features and ftp features where all messed up took them hours to figure it out in multiple calls and tickets.
So now i think i got it all working i load my site through VWD onto my server (www.contentiousweb.com) All of my front end code works fine as far as form validation and links.
When i hit my submit buttons that would execute my c# code nothing happens at all. not a thing. When the forms are filled out wrong the validation works. I got no errors or anything. i like dont know where to start. Is it my code there server how much can i rely on VWD in being right because i cannot rely on my self lol.
Webconfig file. (i swapped out my pw and e-mail)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Ralph <********#hotmail.com>">
<network enableSsl="true" host="smtp.live.com" userName="*************#hotmail.com" password="***********" port="587" />
</smtp>
</mailSettings>
</system.net>
Bellow is the button.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string fileName = Server.MapPath("_TextFiles/ContactForm.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", nameBox.Text);
mailBody = mailBody.Replace("##Email##", emailBox.Text);
mailBody = mailBody.Replace("##Subject##", subBox.Text);
mailBody = mailBody.Replace("##Message##", MsgField.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Response from Contact Page";
myMessage.Body = mailBody;
myMessage.From = new MailAddress("******", "Contact");
myMessage.To.Add(new MailAddress("******", " Server"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
Message.Visible = true;
ContactTable.Visible = false;
System.Threading.Thread.Sleep(5000);
}
}
}
Any help would be greatly appresciated. i am new and learning but with my experince and problems with hostgator i think that it is something on there end because everything else has been. i am clueless.
Please let me know if there is anymore information i can provide. Thank you for any help
In my own troubleshooting i found this error just now using mozila dev tools.
[18:03:28.399] Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500 # http://contentiousweb.com/ScriptResource.axd?d=EJBSV2JIVC3wCtbtVqDWEZfeOsqUeA-l1kZnjjZKvx15e0cjnzPdj4H78hvszmtfrIhAM96VdUstdDjn1xGAbsydMzIjEQeNWDOz2tihnjEjxDW5esVemHLoHR01oIyUBoZTNPd7atx4-EPBnuVlWYbQIeLdoH_eBXy1j9kav6ac2ptv4Cl8sraaDBGXntVH0&t=ffffffff940d030f:1507
Thanks for any help i am still looking for answers my self.
I got it going. After talking with gatorhost on the phone for four hours we determined that the smtp information they had provided me would not work. They had me change my host to
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="localhost" userName="*************#hotmail.com" password="***********" port="25" />
</smtp>
</mailSettings>
</system.net>
And now it all works no errors. Thank you everyone who helped with ideas.
I don't see in your code assigning the port number or credentials?
This code should work
// SMTP options
string Host = "smtp.mail.emea.microsoftonline.com";
Int16 Port = 587;
bool SSL = true;
string Username = "myname#mydomain.com";
string Password = "mypassword";
// Mail options
string To = "reciever#recieverdomain.com";
string From = "myname#mydomain.com";
string Subject = "This is a test";
string Body = "It works!";
MailMessage mm = new MailMessage(From, To, Subject, Body);
SmtpClient sc = new SmtpClient(Host, Port);
NetworkCredential netCred = new NetworkCredential(Username, Password);
sc.EnableSsl = SSL;
sc.UseDefaultCredentials = false;
sc.Credentials = netCred;
try
{
Console.WriteLine("Sending e-mail message...");
sc.Send(mm);
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}

Operation timed out error

I am hitting a wall with reCaptcha.net
Some background -
I am using reCaptcha-dotnet v1.0.5 which I got from http://code.google.com/p/recaptcha/downloads/list?q=label:aspnetlib-Latest.
I was able to develop a site and make it work locally with reCaptcha validation. When I deploy it to the server (the site is hosted on 1and1.com), I am getting the error below -
The operation has timed out
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The operation has timed
out
I have checked the google forums which advise to have the server allow outbound connections from Port 80. I tried to explain this to the support guy at 1and1.com but I don't think he has a clue at all.
Other than the above, is there anything I could do code-wise to resolve this? Has anybody figured a solution for this?
Appreciate any kind of advise!
This is the code I use for mail configuration and Recaptcha proxy for a web site that is hosted on 1and1 :
1- Web.config (only works if put there !)
<system.net>
<mailSettings>
<smtp from="mail#domain.com">
<network host="smtp.1and1.com" port="25" userName="mymail#domain.com" password="mypassword"/>
</smtp>
</mailSettings>
<defaultProxy>
<proxy usesystemdefault = "false" bypassonlocal="false" proxyaddress="http://ntproxyus.lxa.perfora.net:3128" />
</defaultProxy>
</system.net>
2- Inside a dedicated action in mycontroller :
// ouside the action I've defined the response
private class gapi {public bool success{get;set;}}
public bool SendMail(string firstname, string lastname, string email, string message, string grecaptcha)
{
SmtpClient smtp = new SmtpClient("smtp.1and1.com");
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email);
mail.To.Add("mail#domain.com");
mail.Subject = firstname + " " + lastname;
mail.Body = message;
try
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["secret"] = "6LcEnQYTAAAAAOWzB44-m0Ug9j4yem9XE4ARERUR";
values["response"] = grecaptcha;
values["remoteip"] = Request.UserHostAddress;
var response = client.UploadValues("https://www.google.com/recaptcha/api/siteverify","POST", values);
bool result = Newtonsoft.Json.JsonConvert.DeserializeObject<gapi>((Encoding.Default.GetString(response) as string)).success;
if(!result) return "Something is wrong)";
}
//... verify that the other fields are ok and send your mail :)
smtp.Send(mail);
}
catch (Exception e) { return "Something is wrong)"; }
return "Okey :)";
}
Hope this helps.
Finally got the solution, I got the correct proxy server address from 1and1 and used that. reCaptcha works great now.
Also, for some reason, setting the proxy value in the code using the IWebProxy property of the reCaptcha control did not work. I had to add the tag in web.config under .

MVC Form which sends mail

Basically I have an MVC 3 form which sends a mail to my inbox when someone leaves a message on my site.
For some reason it throws an SmtpException with the message: "Failure sending mail."
[HttpPost]
public ActionResult Contact(string name, string email, string message)
{
string From = "contactform#******.com";
string To = "info#******.com";
string Subject = name;
string Body = name + " wrote:<br/><br/>" + message;
System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage(From, To, Subject, Body);
System.Net.Mail.SmtpClient SMPTobj = new System.Net.Mail.SmtpClient("smtp.**********.net");
SMPTobj.EnableSsl = false;
SMPTobj.Credentials = new System.Net.NetworkCredential("info#*******.com", "*******");
try
{
SMPTobj.Send(Email);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw new Exception();
}
return View();
}
Could this be something to do with testing it locally rather than testing it on a server?
Do you need to set the SmtpClient.Port to your Host email port?
I would recommend you to try not to rethrow a new exception but just use
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
rethrowing an exception resets the stack, so you can't reliably trace the source of the error. In this case (without rethrowing) you can probably see the InnerException and Status properties in visual studio usually this will give you more details on the reason of the failure. (Often isp's block port 25 smtp traffic, in case you are testing locally)
Second you can try to configure all the connection details in web.config rather then hard coded in your application that makes it easier to test changes. See below for an example using gmail:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="username#gmail.com">
<network host="smtp.gmail.com" userName="username#gmail.com" password="password" enableSsl="true" port="587" />
</smtp>
</mailSettings>

SmtpClient .send() error: "message rejected as spam by content filtering"

Here is the code i wrote to send email,
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
sc.UseDefaultCredentials = false;
try
{
m.From = new MailAddress(Sender);
m.To.Add(new MailAddress(Receiver));
m.Subject = Subject;
m.IsBodyHtml = true;
m.Body = Body;
sc.Send(m);
}
catch (Exception ex) { _Exceptions.ManageExceptions(ex); }
And the config file settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="xxx#xxx.com">
<network host="192.168.0.170" userName="setsdom01\user1" password="xxx" port="25" />
</smtp>
</mailSettings>
</system.net>
It executes when i run it from my machine, i try on different PC and it is giving me the following message: ...message rejected as spam by content filtering..
What could be the problem?
I think you need to add NetworkCredential backend code.
var AuthenticationDetails = new NetworkCredential("xxx#", "xxxx");
sc.Credentials = AuthenticationDetails;
This might work
Also look this How to Enable and Configure the Spam Confidence Level Thresholds may be helpful

Categories