System.Net.Mail.SmtpException - Email Sender - c#

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);

Related

Mail sending fails through c# when encryption connection is TLS

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();
}
}

WPF Email Sending error on polish server

This is the code for email sending, but it doesn't give any results, there are no errors , also in debugger there are no alerts:
public void EmailSending()
{
try
{
SmtpClient smtp = new SmtpClient("poczta.silesianet.pl", 587);
smtp.Timeout = 20000;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
NetworkCredential Credentials = new NetworkCredential("userName", PB_AddPassword.Password, "https://poczta.silesianet.pl/");
smtp.Credentials = Credentials;
MailMessage message = new MailMessage("from#mail","to#mail");
message.Subject = "Topic:"
message.IsBodyHtml = true;
message.Body = "Body";
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
smtp.SendAsync(message, accountToken);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
And this is the code for the password, but something is also wrong because it doesn't remember it :
private void PB_AssPassword_TextInput(object sender, TextCompositionEventArgs e)
{
string Pass= PB_AssPassword.Password;
hasło = Environment.GetEnvironmentVariable("Pass");
if (Pass== null)
{
Environment.SetEnvironmentVariable("Pass", "Value1");
}
}
Could anyone help me with this?

How to send an e-mail with C# through Gmail

I am getting an error when trying to send an e-mail through my web service. I have tried enabling access to less secure apps disabling 2-step verification and logging into the account via a web browser. None of the solutions on SO have worked for me. I am still getting:
Error: System.Net.Mail.SmtpException: The SMTP server requires a
secure connection or the client was not authenticated. The server
response was: 5.5.1 Authentication Required.
What can I do to fix this issue?
namespace EmailService
{
public class Service1 : IService1
{
public string SendEmail(string inputEmail, string subject, string body)
{
string returnString = "";
try
{
MailMessage email = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
// set up the Gmail server
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
// draft the email
MailAddress fromAddress = new MailAddress("cse445emailservice#gmail.com");
email.From = fromAddress;
email.To.Add(inputEmail);
email.Subject = body;
email.Body = body;
smtp.Send(email);
returnString = "Success! Please check your e-mail.";
}
catch(Exception ex)
{
returnString = "Error: " + ex.ToString();
}
return returnString;
}
}
}
Just Go here : Less secure apps , Log on using your Email and Password which use for sending mail in your c# code , and choose Turn On.
Also please go to this link and click on Continue Allow access to your Google account
also I edit it little bit :
public string sendit(string ReciverMail)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("YourMail#gmail.com");
msg.To.Add(ReciverMail);
msg.Subject = "Hello world! " + DateTime.Now.ToString();
msg.Body = "hi to you ... :)";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("YourMail#gmail.com", "YourPassword");
client.Timeout = 20000;
try
{
client.Send(msg);
return "Mail has been successfully sent!";
}
catch (Exception ex)
{
return "Fail Has error" + ex.Message;
}
finally
{
msg.Dispose();
}
}
If the above code don't work , try to change it like the following code :
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("YourMail#gmail.com", "YourPassword");

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.

C# Send E-Mail issue

I'm trying to send an e-mail in C#,and I'm having some issues.Whenever I try to send an e-mail,I get a message "Error: Failure to send mail".
Here is my code:
try
{
client.Host = "smtp.gmail.com";
client.Port = 465;
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
MailAddress sendFrom = new MailAddress("from#domain.com");
MailAddress sendTo = new MailAddress("to#domain.com");
MailMessage msg = new MailMessage(sendFrom,sendTo);
msg.Subject = "Subject";
msg.Body = "Body";
client.Send(msg);
}
catch (Exception e)
{
MessageBox.Show("Error:" + e.Message);
}
Also I have this declaration:
public SmtpClient client = new SmtpClient();
public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password");
Hope you can help me.
you can try this and make sure you are using valid login credential and you have internet connection:
MailMessage mail = new MailMessage();
mail.Subject = "Your Subject";
mail.From = new MailAddress("senderMailAddress");
mail.To.Add("ReceiverMailAddress");
mail.Body = "Hello! your mail content goes here...";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
NetworkCredential netCre = new NetworkCredential("SenderMailAddress","SenderPassword" );
smtp.Credentials = netCre;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
Try this code
using System.Net.Mail;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("sender#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = ("e mail subject");
mail.Body = ("message body");
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("sender's username", "sender's password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");

Categories