Can't Send Emails From my Website - asp.net

Here I am in a strange situation. When I send the email from localhost it is working fine but when I upload the page to the server and try to send email, I get the following error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I'm displaying the error message in a label for testing purpose and the try is also misplaced I know, I will set it later.
the code I am using is
if (Page.IsValid)
{
try
{
StringBuilder message = new StringBuilder();
message.Append("Hello My Name is ");
message.Append(txtName.Text);
message.AppendLine();
message.AppendLine("My Contact Number " + txtContactNumber.Text.ToString());
message.AppendLine();
message.AppendLine();
message.AppendLine("My Email Id Is " + txtFromEmailAddress.Text.ToString());
message.AppendLine();
message.Append(txtEmailBody.Text);
MailMessage mailMessage = new MailMessage("xxx#gmail.com", "yyy#gmail.com");
mailMessage.Subject = "New Client Query";
mailMessage.Body = message.ToString();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);
//smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxx#gmail.com",
Password = "password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
txtContactNumber.Text = "";
txtFromEmailAddress.Text = "";
txtName.Text = "";
txtEmailBody.Text = "";
lblEmailStatus.Text = "Email Sent Successfully.";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
catch(Exception ex)
{
lblEmailStatus.Text = ex.Message + " <br> " + ex.Source;
}
}
else
{
lblEmailStatus.Text = "Error! Email Not Sent ";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
I have googled for a couple of hours and checked links at this site as well but I still cant figure it out.
Now I request you guys here if any one have any solutions / hint.

Try this
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}

i got the reason finally .
the email i was sending emails from was kind of hacked some days before and for the security reasons google team had kind of marked my email as unsecure . i changed the emails address and it is working fine thanks you all.

Based on the Google Gmail Documentation it would appear that the Port should be 587 not 25. I found a few other questions that seem to be related here and here.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;

Related

Check failure response of email

How to check failure response in email send method using Asp.Net.
The Problem is i didn't get the failure exception.
Please suggest better way.
Here is my code, i'm trying to access the email failure exception...
public static bool sendMail(string strTo, string strSubject, string strName, string strbody)
{
try
{
strName = strName == "" ? "Sir/Madam" : ("Dear " + strName + ",");
StringBuilder mailbody = new StringBuilder();
SmtpClient mailClient = null;
MailMessage message = null;
mailClient = new SmtpClient();
message = new MailMessage();
mailClient.Host = ConfigurationManager.AppSettings["SMTP_MAIL_SERVER"];
mailClient.Port = int.Parse(ConfigurationManager.AppSettings["PORT"]);
//network credentials
string strMailUserName = ConfigurationManager.AppSettings["FROM_ADDR"];
string strMailPassword = ConfigurationManager.AppSettings["FROM_ADDR_PASS"];
string strWebSiteURL = ConfigurationManager.AppSettings["LinkTosite"];
mailClient.EnableSsl = true;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strMailUserName, strMailPassword);
mailClient.UseDefaultCredentials = true;
mailClient.Credentials = SMTPUserInfo;
string strFromMail = ConfigurationManager.AppSettings["FROM_ADDR"];
MailAddress fromAddress = new MailAddress(strFromMail, "TEST (Administrator)");
message.From = fromAddress;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
//to mail address
message.To.Add(strTo);
message.Subject = "ChatOnGo : " + strSubject;
//mailbody.AppendFormat("<link href='" + strWebSiteURL + "admin/css/bestlogin.css' rel='stylesheet' type='text/css' />");
mailbody.AppendFormat("<div class='dlogin_bg'><div class='dlogin_bg_top'></div><div class='dlogin_bg_bottom'><h2>" + strName + "</h2>");
mailbody.AppendFormat(strbody);
mailbody.AppendFormat("<br/><br/><span>Regards,<br /><a href='" + strWebSiteURL + "'>ChatOnGo Admin</a></span></div></div>");
message.Body = mailbody.ToString();
message.IsBodyHtml = true;
mailClient.SendMailAsync(message);
message = null;
mailClient = null;
return true;
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine(ep.Message);
return false;
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
return false;
}
}
I assume you are using gmail to send email.
You should send the email at least once and if the email is not valid you will receive failure notification.
You can create a nightly/hourly job to check these failure emails and mark them as invalid in your database.
Below is the link to read emails programatically :
http://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx
I hope this helps!
I am not sure but can you try to send mail without Async (SendMailAsync), just try to call normal send method, probably you will get exception details.

Email Is not sending successfully from Asp.net application

I am trying to send Email from My asp.net web application which i have developed only for practice purpose but it is not working at all i tried so many things, so many times from google and youtube also but it is not working at all. please do help me if possible.....
one more thing i am doing it in college campus and their firewall is on so i tried it from another network also still it is not working...???
public bool sendMail(string from, string to, string subject, string body)
{
bool flag = false;
var message = new MailMessage();
try
{
message.To.Clear();
message.To.Add(new MailAddress(to));
message.From = new MailAddress(from);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "Email#mail.com",
Password = "password"
};
smtp.Credentials = credential;
smtp.Host = "smtp-mail.outlook.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Send(message);
}
flag = true;
}
catch (Exception ex)
{
}
return flag;
}

Hitting Gmail smtp server using C# but getting few errors. Please suggest

I am trying to hit gmail smtp server from my C# web application, But getting following errors :
1) Failure Sending Message
2) "The operation has timed out."
Following is my code,
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(to);
message.Subject = Name;
message.IsBodyHtml = true;
message.Body = "Some Message";
smtpClient.Host = "smtp.gmail.com"; // We use gmail as our smtp client
smtpClient.Port = 465; //587 for TLS 465 or 25 SSL
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(from, fromPassword);
smtpClient.Timeout = 50000;
smtpClient.Send(message);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
Please Suggest i have tried using Port 587 as well, but both showing the same error.
This link below in greatest details explains how you can do this (in several ways)
static void Main(string[] args)
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Your gmail email address
oMail.From = "gmailid#gmail.com";
// Set recipient email address
oMail.To = "support#emailarchitect.net";
// Set email subject
oMail.Subject = "test email from gmail account";
// Set email body
oMail.TextBody = "this is a test email sent from c# project with gmail.";
// Gmail SMTP server address
SmtpServer oServer = new SmtpServer("smtp.gmail.com");
// Set 465 port
oServer.Port = 465;
// detect SSL/TLS automatically
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// Gmail user authentication
// For example: your email is "gmailid#gmail.com", then the user should be the same
oServer.User = "gmailid#gmail.com";
oServer.Password = "yourpassword";
try
{
Console.WriteLine("start to send email over SSL ...");
oSmtp.SendMail(oServer, oMail);
Console.WriteLine("email was sent successfully!");
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
}

Email goes into Junk folder from asp.Net app

I have functionality in my site which sends a email to an id .. Email contains a link to a webpage and a security key .. But the problem is it goes into the junk folder
I'm using free hosting by Somee.com
Code:
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Body = ("Copy The Link And paste It In Them follow Link Download </br>"+ encoded_url);
message.From = new MailAddress("lz-wag#hotmail.com");
message.To.Add(TextBox2.Text);
message.Subject = user + " Has Share The File With You";
try{
SmtpClient client = new SmtpClient();
client.Host = "smtp.live.com";
client.EnableSsl = true;
System.Net.NetworkCredential networkcred = new System.Net.NetworkCredential();
networkcred.UserName = "lz-wag#hotmail.com";
networkcred.Password = "password";
client.Port = 587;
client.Credentials = networkcred;
client.Send(message);
sendFile.Visible = false;
Label1.Visible = true;
Label1.Text = "Your File Has Been Shared";
}
catch(Exception ex){
Label1.Visible = true;
Label1.Text = "Your File Is Not Shared";
//Label1.Text = ex.ToString(); ;
}
Whether or not the email goes into the junk mail folder is a function of the email client, not a function of how you are sending the email.
However, FYI, both the MailMessage and the SmtpClient implement IDisposable, so should be in using blocks. Something like this:
using (MailMessage message = new MailMessage())
{
// ...
using (SmtpClient client = new SmtpClient())
{
// ...
client.Send(message);
}
}
I also suggest that you log the exception somewhere, or you'll never know what went wrong when something goes wrong.

how to send email through asp.net web api

i am making a windows phone app in which i want to give the forgot password functionality.
the app will send a email to stored email id of the user when he will press on forget password button.
As there is no smtp class available in windows phone , so i want to make a asp.net web api which will receive email id(and password) from the app and will send an email to that id.
I am new in web services and have 0 knowledge of this
please guide me how to achieve this task and if anyone can provide the code, there must be some web service available like this.
Here is an example of a function that sends an email you can use. Also, there are couple links below that can guide you in creating web service in ASP.NET
In reality, you don’t need to create a web service for this (although it’s recommended). You can create a quick and dirty web form where you pass parameters like this example.com/sendemail.aspx?account=jack.smith&id=223232343
private static void SendEmail(string from, string from_name, string to, string cc, string bcc, string subject, string body, bool isHtml)
{
SmtpClient mailClient = new SmtpClient(Config.SmptSettings.Server);
mailClient.Credentials = new NetworkCredential(Config.SmptSettings.UserName, Config.SmptSettings.Password);
mailClient.Port = Config.SmptSettings.Port;
MailMessage message = new MailMessage();
if (!string.IsNullOrEmpty(from_name))
{
message.From = new MailAddress(from, from_name);
}
else
{
message.From = new MailAddress(Formatter.UnFormatSqlInput(from));
}
message.To.Add(new MailAddress(to));
if (!string.IsNullOrEmpty(bcc, cc))
{
message.CC.Add(cc);
message.Bcc.Add(bcc);
}
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = isHtml;
mailClient.EnableSsl = Config.SmptSettings.SSL;
mailClient.Send(message);
}
## Call this function in your WebApi controller ##
private void sendEmailViaWebApi()
{
string subject = "Email Subject";
string body = "Email body";
string FromMail = "shahid#reckonbits.com.pk";
string emailTo = "reciever#reckonbits.com.pk";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.reckonbits.com.pk");
mail.From = new MailAddress(FromMail);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("shahid#reckonbits.com.pk", "your password");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
}
For those using .NET Core, note that there is currently no support for sending emails.
See the following issue for .NET Core via GitHub:
https://github.com/dotnet/corefx/issues/1006
A an alternative solution has been implemented - MailKit:
https://github.com/jstedfast/MailKit
string random;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmailId from tblEmail where EmailId='" + txtemail.Text + "'", con);
SqlDataReader dr =cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
s1 = dr.GetString(0);
}
}
dr.Close();
if (s1.Equals(txtemail.Text))
{
Session["Email"] = txtemail.Text;
try
{
Random rndm = new Random();
random = rndm.Next(99999).ToString();
MailMessage message = new MailMessage();
message.From = new MailAddress("yourid#gmail.com");
message.To.Add(new MailAddress(txtemail.Text));
message.Subject = " Hello... This is Your Serial No to change your password:";
message.Body = random.ToString();
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;//Gmail port number
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("yourid#gmail.com", "yourpassword");
client.Send(message);
SqlCommand cmd1 = new SqlCommand("insert into tblRandom values('" + txtemail.Text + "','" + random.ToString() + "')", con);
cmd1.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Security Code Successfully Sent in Your Email Id')</script>");
Response.Redirect("~/anotherpage.aspx");
}
catch (Exception)
{
// Response.Write(ee.Message);
lblmsg.Text = "Please Enter Email-Id..";
lblmsg.Visible = true;
//MessageBox.Show("Please Enter Email-ID");
//Response.Write("<script>alert('Please Enter Email-ID')</script>");
}
}
else
{
lblmsg.Text = "Please Enter Correct Email-Id..";
lblmsg.Visible = true;
}
}

Resources