I have c# code to send mail. The code is working fine for gmail,yahoo configuration. But for hotmail sometimes the mail is sent and sometimes the mail is not sent. I observed that the response time for yahoo mail is better compare to gmail. But hotmail has very poor response compare to yahoo,gmail.
What will be reason? how to configure hotmail to get good response.
this is my code to send mail :
private void button2_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage();
message.To.Add("user_name");
message.From = new MailAddress("user_name");
message.Subject = "Email Confirmation";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.Port=587
client.Host="smtp.live.com";
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("user_name", "password");
if (mail_server == "smtp.gmail.com" || mail_server == "smtp.live.com")
{
client.EnableSsl = true;
}
client.UseDefaultCredentials = false;
client.Credentials = nc;
Ping p = new Ping();
bool result = false;
int i = 10;
do
{
PingReply reply = p.Send("smtp.live.com", 587);
if (reply.Status == IPStatus.Success)
{
result = true;
} Thread.Sleep(500);
i--;
} while (result == false && i != 0);
if (result == true)
{
client.Send(message);
MessageBox.Show("Email sent successfully");
}
else
{
MessageBox.Show("Email not sent");
}
}
If you are trying the above code to Send Email, it will obviously not be able to send it, I dont know for what reason you are using the Ping class to send email.
Fixed Code :
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage();
message.To.Add("user_name");
message.From = new MailAddress("user_name");
message.Subject = "Email Confirmation";
message.BodyEncoding = Encoding.UTF8;
message.SubjectEncoding = Encoding.UTF8;
client.Port = 587;
client.Host = "smtp.live.com";
NetworkCredential nc = new NetworkCredential("user_name", "password");
string mail_server = "smtp.live.com";
if (mail_server == "smtp.gmail.com" || mail_server == "smtp.live.com")
{
client.EnableSsl = true;
}
client.UseDefaultCredentials = false;
client.Credentials = nc;
try
{
client.Send(message);
}
catch (SmtpException exception)
{
Console.WriteLine(exception.Message);
}
Related
I am setting up mail sending in my code as below
NetworkCredential nc = new NetworkCredential(ConfigurationManager.AppSettings["EmailId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
MailMessage mm = new MailMessage();
mm.From = new MailAddress(SendEmailaddress);
mm.Body = "Test Mail";
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.To.Add(ToEmailAddress);
mm.Subject = "Test";
SmtpClient sp = new SmtpClient();
sp.UseDefaultCredentials = false;
sp.Credentials = nc;
sp.EnableSsl = true;
sp.DeliveryMethod = SmtpDeliveryMethod.Network;
sp.Port = 587
sp.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
sp.Send(mm);
A error is thrown at the time of mail sending. Mail sending works if I configure outlook on the same PC with these settings with TLS as encrypted connnection.
I have checked many posts where it is suggested that EnableSsl = true should be set for TLS to work but it does not work for me. It throws below error
Transaction failed. The server response was: 5.7.1
: Recipient address rejected: Access denied
at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
I have hit a roadblock as no solution is found. is there a setting which needs to be done on server?
protected void SendAlertEmail(string smtpserver, string smtpport, string smtpuser, string smtppass, int ssl, int auth, string subject, string from, string to, string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SplitEmailStrging(from), HttpUtility.HtmlDecode(Request.Form["senderName"]));
string emails = to;
if (emails.Contains(","))
{
string[] emailslist = Regex.Split(emails, #",");
foreach (string email in emailslist)
{
mail.To.Add(SplitEmailStrging(email));
}
}
else
{
if (emails.Contains("<"))
{
mail.To.Add(SplitEmailStrging(emails));
// Response.Write(SplitEmailStrging(emails));
}
else
{
mail.To.Add(emails);
// Response.Write(emails);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlDecode(body);
SmtpClient client = new SmtpClient(smtpserver);
if (int.Parse(smtpport) == 465)
{
client.Port = 25;
}
else
{
client.Port = int.Parse(smtpport);
}
if (ssl == 1)
{
client.EnableSsl = true;
}
else
{
client.EnableSsl = false;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpuser, smtppass);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
}
catch (Exception ex)
{
Response.Write("Error: " + ex.InnerException.Message);
Response.End();
}
}
I have created an email sending function but it keeps getting timed out.
try
{
send.Enabled = false;
MailMessage message = new MailMessage();
message.From = new MailAddress(senderemail.Text);
message.Subject = subject.Text;
message.Body = body.Text;
foreach (string str in recipients.Text.Split(';'))
{
message.To.Add(str);
}
try
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential(senderemail.Text, senderpassword.Text);
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Send(message);
MessageBox.Show("Sent Successfully", "Details");
}
catch
{
SmtpClient client2 = new SmtpClient();
client2.Credentials = new NetworkCredential(senderemail.Text, senderpassword.Text);
client2.Host = "smtp.gmail.com";
client2.Port = 465;
client2.EnableSsl = true;
client2.Send(message);
MessageBox.Show("Sent Successfully", "Details");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
send.Enabled = true;
}
After a port analysis using telnet, I am clueless as to why the code won't execute properly.
Try
client.UseDefaultCredentials = false;
public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.
Net.Mail.SmtpException in output when I send any message using Email Sender application made in C#.
ERROR: System.Net.Mail.Smtp.Exception: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at System.Net.MailCommand.CheckResponse(SmtpStatusCodestatusCde,Stringresponse)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddressfrom,Boolean allowUnicode) at System.Net.Mail.Smtp.Transport.SendMail(MailAddress sender,MailAddressCollection recipients, String deliveryNotify,Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at My_first_project.Form1.button2_Click(Object sender, EventArgs e) in c:\Users\HUSSAM\Documents\Visual Studio 2012\Projects\C#\Projects\My first project\My first project\Form1.cs:line 80
Here is the CODE::
private void button2_Click(object sender, EventArgs e){
try
{
if (!textBox4.Text.Contains("#gmail.com"))
{
MessageBox.Show("You need to provide #gmail email :)");
return;
}
button2.Enabled = false;
MailMessage message = new MailMessage();
message.From = new MailAddress(textBox4.Text);
message.Subject = textBox2.Text;
message.Body = textBox3.Text;
foreach (string s in textBox1.Text.Split(';'))
message.To.Add(s);
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(textBox4.Text, textBox5.Text);
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(message);
}//end try
catch
{
MessageBox.Show("There was error sending the message. Make sure you typed in\r\nyour credentials correctly and that you have an internet connection.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally { button2.Enabled = true; }
}//end button function
Try it:
var mail = new MailMessage();
var smtp = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("email_from");
mail.To.Add("email_to");
mail.Subject = "subject";
mail.Body = "body";
smtp.Port = 587;
smtp.Credentials = new NetworkCredential("user", "password");
smtp.EnableSsl = true;
smtp.Send(mail);
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.