unable to send mail in c# using smtp server - c#

I have a service which is suppose to send the mail to selected users,
the service looks like below
try
{
var smtpHost = System.Configuration.ConfigurationManager.AppSettings["SMTP-HOST"].ToString();//smtp.gmail.com
var fromEmail = System.Configuration.ConfigurationManager.AppSettings["SMTP-USER"].ToString();//My Id
var toEmail = "ibrahim.shaikh#chromeinfosoft.com";
var subject = "test";
var body = "body";
var smtpPort = System.Configuration.ConfigurationManager.AppSettings["SMTP-PORT"].ToString();//465
var smtpPassword = System.Configuration.ConfigurationManager.AppSettings["SMTP-PASSWORD"].ToString();//my password
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(smtpHost);
using (SmtpClient smtp = new SmtpClient(smtpHost))
{
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
SmtpServer.EnableSsl = false;
SmtpServer.Port = Convert.ToInt32(smtpPort);
SmtpServer.Credentials = new System.Net.NetworkCredential(fromEmail, smtpPassword);
SmtpServer.Send(mail);
}
}
catch (Exception ex)
{
// Log the error
}
my config file is below
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SMTP-HOST" value="smtp.gmail.com"/>
<add key="SMTP-PORT" value="465"/>
<add key="SMTP-USER" value="ibrahim.shaikh#chromeinfosoft.com"/>
<add key="SMTP-SSL" value="N"/>
<add key="SMTP-PASSWORD" value ="Password"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
my outlook configuration
Now I am trying to send the mail but the exception is coming.
exception: {"Failure sending mail."}
inner exception: {"Unable to read data from the transport connection: net_io_connectionclosed."} System.Exception {System.IO.IOException}
my email Id and password is correct with port details, still the same error occurred,
any suggestions what I am doing wrong here?

Related

ASP.NET MVC C# Email Notifications on Submit

I would like some advice on Sending Email notifications to Users. I am developing a ticket system and would like the user's to get a notification to the email address they provide on the email field. The same should also be replicated when the ticket has come to a closure.
In app.config or web.config you configure email and password:
<configuration>
<appSettings>
<add key="FromEmail" value="Your Email. EX: abc#abc.com"/>
<add key="FromPassword" value="Your Password of Email"/>
</appSettings>
</configuration>
And in button submit method, use this code:
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("Your Server Mail");
mail.From = new MailAddress(GetAppSetting("FromEmail"));
mail.To.Add("User Email You Want Send");
mail.Subject = "Notifications ";
mail.Body = "Body your mail";
mail.IsBodyHtml = true;
SmtpServer.Port = your_port;
SmtpServer.Credentials = new System.Net.NetworkCredential(GetAppSetting("FromEmail"), GetAppSetting("FromPassword"));
//SmtpServer.EnableSsl = true;
try
{
SmtpServer.Send(mail);
MessageBox.Show("Email Sent!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Error when send mail, Error Code: " + ex.Message);
}

sending email from smtp gmail in c#

i am trying to send email from my web app. i am using smtp gmail for the same. but for some reasons i am not able to send a mail.. i have tried port numbers like 25,465,587 but none of these are working....
public static void SendMail(string host, string senderName, string frmAddress, string toAddress, int port, string subject, string messageText)
{
String smtpHost, port1;
smtpHost = ConfigurationManager.AppSettings["smtphost"].ToString();
port1 = ConfigurationManager.AppSettings["smtpport"].ToString();
SmtpClient mailClient = new SmtpClient(smtpHost, Convert.ToInt16(port1));
mailClient.EnableSsl = true;
NetworkCredential cred = new NetworkCredential();
cred.UserName = ConfigurationManager.AppSettings["username"].ToString();
cred.Password = ConfigurationManager.AppSettings["password"].ToString();
mailClient.Credentials = cred;
mailClient.UseDefaultCredentials = false;
//mailClient.Credentials = cred;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
try
{
MailAddress fromAddress = new MailAddress(frmAddress, senderName);
message.From = fromAddress;
message.To.Add(toAddress);
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = messageText;
mailClient.Send(message);
//Response.Write("<script language='javascript' type='text/javascript'>window.alert('Email Successfully Sent.');</script>");
}
catch
{
//Response.Write("<script language='javascript' type='text/javascript'>window.alert('Send Email Failed '" + ex.Message + ");</script>");
}
}
calling this method:
protected void btnMail_Click1(object sender, EventArgs e)
{
string from = txtEmail.Text;
string to = "my gmail id";
string message = taMessage.InnerText;
Global.SendMail(ConfigurationManager.AppSettings["smtphost"].ToString(), txtName.Text, from, to, Convert.ToInt32(ConfigurationManager.AppSettings["smtpport"]), "Enquiry", taMessage.InnerText);
}
web.config settings :
<appSettings>
<add key="smtphost" value="smtp.gmail.com"/>
<!--<add key="smtphost" value="103.231.41.229"/>-->
<add key="smtpport" value="587"/>
<!--<add key="port" value="25"/>-->
<add key="username" value="my gmail id/>
<add key="password" value="my password"/>
<add key="From" value="my gmail id"/>
</appSettings>
Exception : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication
Its a security issue, Gmail by default prevents access for your mail account from custom applications. You can set it up to accept the login from your application.
After Logging in to your mail ,
https://www.google.com/settings/security/lesssecureapps
Update:
msg.IsBodyHtml = true;
Try this:-
protected void Button1_Click(object sender, EventArgs e)
{
// body
//subject
//reciever id
sendmail(recieverID, subject, body);
}
method for sending mail
protected void sendmail(string reciever, string subject, string body)
{
string senderID = "sender email id";
string pwd = "password ";
string result = "Message Sent Successfully";
try
{
SmtpClient smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(senderID, pwd),
Timeout = 30000
};
MailMessage msg = new MailMessage(senderID, reciever, subject, body);
msg.IsBodyHtml = true;
smtpClient.Send(msg);
}
catch
{
result = "Error Sending Mail";
}
Response.Write(result );
}
OR
U can also go through this link

Sending email via GMail: A connection attempt failed because the connected party did not properly respond

I am using This post and This Post to create simple email sending Application on c# console App. But I am getting error when sent email on gmail ...
{"A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond XXX"}
Here is my Code :
class Program
{
private static string to = "XXX#gmail.com";
private static string from = "XXX#gmail.com";
private static string subject="07/10/14";
private static string body;
private static string address = "XXX#gmail.com";
static void Main(string[] args)
{
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials =
new System.Net.NetworkCredential(address, "YYYYY");
smtp.Send(mail);
Console.WriteLine("Sent");
Console.ReadLine();
}
}
My App.Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
</appSettings>
<system.net>
<mailSettings>
<smtp from="XXX#gmail.com">
<network defaultCredentials="false"
userName="XXX#gmail.com"
password="YYYYY"
host="smtp.gmail.com" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
I have read similar post ..Some suggest convert url into stream ..I did not get it ..Some says problem might be in internet connection ..other says set smtp server to 587 ..I have applied all changes ..still it shows same error
Please Suggest
I have Solved this problem ...
Just use your Hosting Company Smtp and Port ..not gmail or other one..If you are sending from a hosting company ....Consult your IT Desk for providing your company smtp address and port ..I did that..that solved the Issue
This is My Working Code ..it is also sending to gmail by company SMTP
class Program
{
private static string to = "XXXXr#youHostingComapny.com";
private static string from = "YYYYY#youHostingComapny.com";
private static string subject = "test Mail sent By Code";
private static string body = "Mail sent By Code";
static void Main(string[] args)
{
try
{
MailMessage mail = null;
using (mail = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
mail.Subject = subject;
mail.Body = body;
mail.To.Add("ZZZZZZZZ#gmail.com");
SmtpClient smtpMail = null;
using (smtpMail = new SmtpClient("HostingComapny smtp Address"))
{
smtpMail.Port = Hosting Company Port No.;
smtpMail.EnableSsl = false;
smtpMail.Credentials = new NetworkCredential("youruserName", "yourPassword");
smtpMail.UseDefaultCredentials = false;
// and then send the mail
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpMail.Send(mail);
Console.WriteLine("sent");
Console.ReadLine();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}

sending mail in asp.net-also using web config

i am tryiung to create a contact us page ,where the user clicks submit and sends an email to me, i looked at some examples, but they seem to be hard coding their email credentials into the code, i found out that for security m you can store the username and password in the webconfig file, below is my web config code and my default aspx.cs code, could anybody please help me solve the problem, this is the error i get
The remote name could not be resolved: 'smtp.gmail.com,587' Line 45: mailClient.Send(message);
Here is my appsettings and code:
<appSettings>
<add key="PFUserName" value="myemail#gmail.com"/>
<add key="PFPassWord" value="mypassword"/>
<add key="MailServerName" value="smtp.gmail.com,587"/>
</appSettings>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net;
namespace WebApplication2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
SendMail(txtEmail.Text, txtComments.Text);
}
private void SendMail(string from, string body)
{
string Username = WebConfigurationManager.AppSettings["PFUserName"].ToString();
string Password = WebConfigurationManager.AppSettings["PFPassWord"].ToString();
string MailServer = WebConfigurationManager.AppSettings["MailServerName"].ToString();
NetworkCredential cred = new NetworkCredential(Username, Password);
string mailServerName = ("smtp.gmail.com,587");
MailMessage message = new MailMessage(from, Username, "feedback", body);
SmtpClient mailClient = new SmtpClient("smtp.gmail.com,587");
mailClient.EnableSsl = true;
mailClient.Host = mailServerName;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = cred;
mailClient.Send(message);
message.Dispose();
}
}
}
You need to set SMTP setting inside the mailSettings configuration in web.config like this
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="my#mail.com">
<network host="smtp.gmail.com" port="587" userName="myemail#gmail.com" password="mypassword" />
</smtp>
</mailSettings>
</system.net>
Your server name is smtp.gmail.com (remove the 587 from there). 587 is the port that smtp is using. So put this value in host property.
C# Code:
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("sender#mail.com"));
mailMessage.Subject = "mailSubject";
mailMessage.Body = "mailBody";
smtpClient.Send(mailMessage);
This is what I currently use in my Web Config with some obvious edits
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="username#gmail.com">
<network defaultCredentials="false" host="smtp.gmail.com" port="587" userName=username" password="xxxxxxxxxxxx" />
</smtp>
</mailSettings>
</system.net>
in the CS file
using System.Net.Mail;
and
MailMessage myMessage = new MailMessage();
//subject line
myMessage.Subject = Your Subject;
//whats going to be in the body
myMessage.Body = Your Body Info;
//who the message is from
myMessage.From = (new MailAddress("Mail#Mail.com"));
//who the message is to
myMessage.To.Add(new MailAddress("Mail#Mail.com"));
//sends the message
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
for sending.
Your host name should be "smtp.gmail.com" and then set mailClient.Port to 587.
why did you dont compile in a class to make a dll?
Well, i use this code, enjoy :)
MailMessage mail = new MailMessage();
try
{
mail.To.Add(destinatario); // where will send
mail.From = new MailAddress("email that will send", "how the email will be displayed");
mail.Subject = "";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
// mail body
mail.Body = "email body";
// send email, dont change //
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("gmail account", "gmail pass"); // set 1 email of gmail and password
client.Port = 587; // gmail use this port
client.Host = "smtp.gmail.com"; //define the server that will send email
client.EnableSsl = true; //gmail work with Ssl
client.Send(mail);
mail.Dispose();
return true;
}
catch
{
mail.Dispose();
return false;
}
<configuration>
<!-- Add the email settings to the <system.net> element -->
<system.net>
<mailSettings>
<smtp>
<network
host="relayServerHostname"
port="portNumber"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>
...
</system.web>
</configuration>
above is web.config and here is back-end code :
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;
using System.Net.Configuration;
private void Email(string email, string pass, string customername)
{
SmtpSection smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
MailMessage mm = new MailMessage(smtp.Network.UserName,email);
mm.Subject = "Thank you for Registering with us";
mm.Body = string.Format("Dear {0},<br /><br />Thank you for Registering with <b> Us. </b><br /> Your UserID is <b>{1}</b> and Password is <b> {2} </b> <br /><br /><br /><br /><br /><b>Thanks, <br />The Ismara Team </b>", customername, email, pass);
mm.IsBodyHtml = true;
try
{
using (SmtpClient client = new SmtpClient())
{
client.Send(mm);
}
}
catch (Exception ex)
{
throw new Exception("Something went wrong while sending email !");
}
}
system will automatically get the details of smtp from web.config

Sending email with ASP.net

So i've been searching stackoverflow for a way to send emails using a gmail account via a asp website...
I've tried many ways including Sending email in .NET through Gmail which seemed to be the best due to amount of upvotes he got.
However sadly it still doesn't work for me! I keep getting a time out.
Here's my code:
var fromaddress = new MailAddress("from#gmail.com", "from");
var toaddress = new MailAddress("to#address.com", "to");
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.EnableSsl = true;
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
in my web.config I have
<system.net>
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" port="587"/>
</smtp>
</mailSettings>
</system.net>
According to several sites i've visited this should work!!! .. but it doesn't.
Is there still anything i'm doing wrong?
You never set the login add this before your smtpClient.Send() Method.
NetworkCredential NetCrd = new NetworkCredential(youracc, yourpass);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = NetCrd;
Load the web.config via ConfigurationManager if it does not work automatically.
As suggested on this page, try installing telnet to see if you can connect to the mail server. It could be a firewall issue on your server. You can also try using another port as suggested in the link.
Your code seems fine to me.
Try to deliberately enter false credentials. If you get a different errormessage you are connected to gmail and there is a problem there.
If you get the same timeout problem, it is probably not a software thing but a firewall issue.
longshot - update
Perhaps there is a web.config issue? Try to specify everything in code like this. I have this working in real life with Gmail so if this does not work it definitely is a firewall/connection thing.
SmtpClient mailClient = new SmtpClient();
//This object stores the authentication values
System.Net.NetworkCredential basicCredential =
new System.Net.NetworkCredential("username#mydomain.com", "****");
mailClient.Host = "smtp.gmail.com";
mailClient.Port = 587;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCredential;
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("info#mydomain.com", "Me myself and I ");
message.From = fromAddress;
//here you can set address
message.To.Add("to#you.com");
//here you can put your message details
mailClient.Send(message);
Good luck..
Can you try this out?
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromAddress"], ConfigurationManager.AppSettings["displayName"]); //Default from Address from config file
MailAddress toAddress = new MailAddress("abc#gmail.com", "from sender");
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = ConfigurationManager.AppSettings["smtpClientHost"];
//Default port will be 25
smtpClient.Port = int.Parse(ConfigurationManager.AppSettings["portNumber"]); //From config file
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(toAddress);
message.Subject = ConfigurationManager.AppSettings["Subject"]; //Subject from config file
message.IsBodyHtml = false;
message.Body = "Hello World";
smtp.DeliveryMethod = SmtpDeliveryMethod.NetWork
smtpClient.Send(message);
}
catch (Exception ex)
{
throw ex.ToString();
}
The configuration settings would be,
<configuration>
<appSettings>
<add key="smtpClientHost" value="mail.localhost.com"/> //SMTP Client host name
<add key="portNumber" value="25"/>
<add key="fromAddress" value="defaultSender#gmail.com"/>
<add key="displayName" value="Auto mail"/>
<add key="Subject" value="Auto mail Test"/>
</appSettings>
</configuration>
Put these settings EnableSSL = true and defaultCredentials="false" in your web.config settings. Gmail smtp server requires SSL set to true and mailclient.UseDefaultCredentials = false should be false if you are providing your credentials.
Update Web.Config Settings:
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" defaultCredentials="false" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
And check this shorter code to send mail after providing settings in the web.config. even it send email much fast rather then specifying setting while creating the smtpclient setting in the mail sending function.
Public void SendEmail(string toEmailAddress, string mailBody)
{
try
{
MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(toEmailAddress);
mailMessage.Subject = "Mail Subjectxxxx";
mailMessage.Body = mailBody;
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
return "Mail send successfully";
}
catch (SmtpException ex)
{
return "Mail send failed:" + ex.Message;
}
Working very much fine at my side..
var smtpClient = new SmtpClient(gmailSmtpServer, gmailSmtpPort)
{
Credentials = new NetworkCredential(FromGEmailAddress, FromGEmailAddressPassword),
EnableSsl = true
};
try
{
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
catch (Exception exc)
{
// error
return false;
}

Categories