sending email from smtp gmail in c# - 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

Related

Asp.Net sending outlook email and get this 5.7.57 SMTP Client was not authenticated to send anonymous mail during MAIL FROM

I am sending outlook email with asp.net c#.
When I run this, I got an error at (smtp.Send(fromAddress, toAddress, subject, body);) I search online and try to solve at came up with nothing. Please send help. I really appreciate it.
protected void btn_Click(object sender, EventArgs e)
{
string eml = "xxx#mymail.com";
var fromAddress = "xxx#outlook.com";
var toAddress = eml;
const string fromPassword = "password";
string subject = "Subject testing";
string body = "Welcome..";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com");
{
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(fromPassword, fromPassword);
smtp.EnableSsl = true;
smtp.Credentials = credentials;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
At the line:
new System.Net.NetworkCredential(fromPassword, fromPassword)
You have fromPassword for both parameters instead of having the username and the password
new System.Net.NetworkCredential(fromAddress, fromPassword)

C# receive error sending a email

ERROR: Service not available, closing transmission channel. The server response was: Resources temporarily unavailable - Please try again later
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "mail#yahoo.com";
string password = "mailpass";
string emailTo = "sendemail#yahoo.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
//mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
//mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
What should I do?
You need to make sure an external application has permission to send emails through your email before you can proceed.

Sending mail from local host to Gmail but mail is not sent

My Code on Button_Click is
Massage = "Name :" + txtname.Text + "\nEmail :" + txtemail.Text + "\nPhone :" + TextBox3.Text + "\nMassage :" + TextBox4.Text;
eMail.Mail(null, "contact us", "vermarajneesh344#gmail.com", null, null, "contact us", Massage, null, null);
and the code behind is
public class eMail
{
public static bool Mail(string FromEmailAddress, string FromDisplayName, string ToAddress, string ToAddressCC, string ToAddressBCC, string Subject, string bodytxt, string HostName, string AttachFileName)
{
bool functionReturnValue = false;
//*******example
//// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
//// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
if (string.IsNullOrEmpty(FromEmailAddress))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["FromEmailAddress"].ToString()))
FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
MailAddress fromAddress = new MailAddress(FromEmailAddress, FromDisplayName);
// // You can specify the host name or ipaddress of your server
//// Default in IIS will be localhost
if (string.IsNullOrEmpty(HostName))
{
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["HostName"].ToString()))
HostName = "smtp.gmail.com"; //"mail.osmor.org";
else
HostName = ConfigurationManager.AppSettings["HostName"].ToString();
}
smtpClient.Host = HostName;
////Default port will be 25
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smtpClientPort"].ToString()))
smtpClient.Port = 465;
else
smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpClientPort"].ToString());
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ESSL"].ToString()))
{
if (ConfigurationManager.AppSettings["ESSL"].ToString() == "true")
smtpClient.EnableSsl = true;
else
smtpClient.EnableSsl = false;
}
////From address will be given as a MailAddress Object
message.From = fromAddress;
//// To address collection of MailAddress
if (string.IsNullOrEmpty(ToAddress))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ToAddress"].ToString()))
ToAddress = ConfigurationManager.AppSettings["ToAddress"].ToString();
string[] tmp = null;
int i = 0;
tmp = Mainclass.SplitByString(ToAddress, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.To.Add(tmp[i].ToString());
//"firsttime#sector-17.com")
message.Subject = Subject;
//"Feedback"
}
//// CC and BCC optional
//// MailAddressCollection class is used to send the email to various users
// // You can specify Address as new MailAddress("admin1#yoursite.com")
if (string.IsNullOrEmpty(ToAddressCC))
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ToCC"].ToString()))
ToAddressCC = ConfigurationManager.AppSettings["ToCC"].ToString();
if (!string.IsNullOrEmpty(ToAddressCC))
{
tmp = Mainclass.SplitByString(ToAddressCC, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.CC.Add(tmp[i].ToString());
//
}
}
//ToAddressBCC = "amangargptl#gmail.com";
// // You can specify Address directly as string
if (!string.IsNullOrEmpty(ToAddressBCC))
{
tmp = Mainclass.SplitByString(ToAddressBCC, ",");
for (i = 0; i <= tmp.Length - 1; i++)
{
message.Bcc.Add(new MailAddress(tmp[i].ToString()));
}
}
// //message.Bcc.Add(new MailAddress("admin4#yoursite.com"));
////Body can be Html or text format
// //Specify true if it is html message
message.IsBodyHtml = true;
String UserName, Password;
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UserName"].ToString()))
UserName = ConfigurationManager.AppSettings["UserName"].ToString();
else
UserName = "UserName";
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Password"].ToString()))
Password = ConfigurationManager.AppSettings["Password"].ToString();
else
Password = "Password";
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
//// Message body content
message.Body = bodytxt;
if (!string.IsNullOrEmpty(AttachFileName))
message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("~/" + AttachFileName)));
// // Send SMTP mail
smtpClient.Send(message);
// lblStatus.Text = "Email successfully sent.";
functionReturnValue = true;
}
catch (Exception ex)
{
bodytxt = "Send Email Failed.<br>" + ex.Message;
//;
//Mainclass.WriteErorrFile(ex.Message, "Macadamia", "Mail");
//c.msg(ex.Message, response)
functionReturnValue = false;
// throw;
}
return functionReturnValue;
}
and code on web.config is
<appSettings>
<add key="bh" value="Travel Holidays"/>
<add key="FromEmailAddress" value="info#Travelholidays.com"/>
<add key="ToAddress" value=""/>
<add key="ToCC" value=""/>
<add key="HostName" value="smtp.gmail.com"/>
<add key="UserName" value="info#Travelholidays.com"/>
<add key="Password" value="password"/>
<add key="smtpClientPort" value="587"/>
<add key="ESSL" value="true"/>
</appSettings>
Thanks..
help would be greatly appreciated
Use these setting in your web.config
<system.net>
<mailSettings>
<smtp from="sender#gmail.com ">
<network host="smtp.gmail.com" defaultCredentials="false"
port="587" enableSsl="true" userName="Sender#gmail.com" password="*******" />
</smtp>
</mailSettings>
</system.net>
In your .aspx.cs use
StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("Email body here");
MailMessage email = new MailMessage();
email.To.Add(new MailAddress("ReceiverEmailAddress"));
email.Subject = "Mail Subject";
email.From = new MailAddress("sender#gmail.com");
email.Body = emailMessage.ToString();
email.IsBodyHtml = true;
//Send Email;
SmtpClient client = new SmtpClient();
client.Send(email);
That's it. Hope it works

Send email through SMTP

I have contact page on my website and I want users to enter Their name and email id (no password) and send email on button click.
I did Google and all solutions i am getting requires user password,
public static void SendMessage(string subject, string messageBody, string toAddress, string ccAddress, string fromAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress(fromAddress);
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtpHost";
smtp.Port =portno;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail", "fromPassword");
smtp.Timeout = 20000;
}
// Send the e-mail message
smtp.Send(message);
}
But I don't want to force users to enter password. Is there any other solution using SMTP?
The error I am getting is 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
I have this function in my utility class , and it works like a charm.
public static bool SendMail(string Email, string MailSubject, string MailBody)
{
bool isSent = false, isMailVIASSL = Convert.ToBoolean(ConfigurationManager.AppSettings["MailServerUseSsl"]);
string mailHost = ConfigurationManager.AppSettings["MailServerAddress"].ToString(),
senderAddress = ConfigurationManager.AppSettings["MailServerSenderUserName"].ToString(),
senderPassword = ConfigurationManager.AppSettings["MailServerSenderPassword"].ToString();
int serverPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]);
MailMessage msgEmail = new MailMessage(new MailAddress(senderAddress), new MailAddress(Email));
using (msgEmail)
{
msgEmail.IsBodyHtml = true;
msgEmail.BodyEncoding = System.Text.Encoding.UTF8;
msgEmail.Subject = MailSubject;
msgEmail.Body = MailBody;
using (SmtpClient smtp = new SmtpClient(mailHost))
{
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = isMailVIASSL;
smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
smtp.Port = serverPort;
try
{
smtp.Send(msgEmail);
isSent = true;
}
catch (Exception ex)
{
throw ex;
}
}
}
return isSent;
}
<!-- Mail Server Settings -->
<add key="MailServerAddress" value="smtp.gmail.com" />
<add key="MailServerPort" value="25" />
<add key="MailServerSenderUserName" value="username#gmail.com" />
<add key="MailServerSenderPassword" value="password" />
<add key="MailServerUseSsl" value="True" />

Sending an email programmatically through an SMTP server

Trying to send an email through an SMTP server, but I'm getting a nondescript error on the smtp.Send(mail); snippet of code.
Server side, the relay IP addresses look correct. Scratching my head about what I'm missing.
MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text);
mail.From = new MailAddress("no-reply#company.us");
mail.Subject = "Thank you for your submission...";
mail.Body = "This is where the body text goes";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mailex.company.us";
smtp.Credentials = new System.Net.NetworkCredential
("AdminName", "************");
smtp.EnableSsl = false;
if (fileuploadResume.HasFile)
{
mail.Attachments.Add(new Attachment(fileuploadResume.PostedFile.InputStream,
fileuploadResume.FileName));
}
smtp.Send(mail);
Try adding smtp.DeliveryMethod = SmtpDeliveryMethod.Network; prior to send.
For reference, here is my standard mail function:
public void sendMail(MailMessage msg)
{
string username = "username"; //email address or domain user for exchange authentication
string password = "password"; //password
SmtpClient mClient = new SmtpClient();
mClient.Host = "mailex.company.us";
mClient.Credentials = new NetworkCredential(username, password);
mClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mClient.Timeout = 100000;
mClient.Send(msg);
}
Typically called something like this:
MailMessage msg = new MailMessage();
msg.From = new MailAddress("fromAddr");
msg.To.Add(anAddr);
if (File.Exists(fullExportPath))
{
Attachment mailAttachment = new Attachment(fullExportPath); //attach
msg.Attachments.Add(mailAttachment);
msg.Subject = "Subj";
msg.IsBodyHtml = true;
msg.BodyEncoding = Encoding.ASCII;
msg.Body = "Body";
sendMail(msg);
}
else
{
//handle missing attachments
}
var client = new SmtpClient("smtp.gmail.com", 587);
Credentials = new NetworkCredential("sendermailadress", "senderpassword"),
EnableSsl = true
client.Send("sender mail adress","receiver mail adress", "subject", "body");
MessageBox.Show("mail sent");
This is Adil's answer formatted for C#:
public static class Email
{
private static string _senderEmailAddress = "sendermailadress";
private static string _senderPassword = "senderpassword";
public static void SendEmail(string receiverEmailAddress, string subject, string body)
{
try
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(_senderEmailAddress, _senderPassword),
EnableSsl = true
};
client.Send(_senderEmailAddress, receiverEmailAddress, subject, body);
}
catch (Exception e)
{
Console.WriteLine("Exception sending email." + Environment.NewLine + e);
}
}
}
You didn't specify the port.
smtp.Port = 1111; // whatever port your SMTP server uses
The SMTP has three different "standard" ports: 25, 465 and 587. According to msdn documentation, the default value for the Port property is 25.

Categories