SmtpException in System.Net.Mail.dll - c#

Im trying to send an email with c#, like so:
public string SendEmail(string employeeEmail, string clientEmail, string subject, string message)
{
MailMessage mailMessage = new MailMessage(employeeEmail, clientEmail)
{
Subject = subject,
Body = message,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = true
};
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
NetworkCredential basicCredential1 = new NetworkCredential("email", "password");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
try
{
if (UserExists(employeeEmail))
{
if (objDAL.ClientExists(clientEmail))
{
client.Send(mailMessage);
return "Email sent";
}
else
{
return "Client email not found";
}
}
else
{
return "Employee email not found.";
}
}
catch
{
return "ERROR";
}
}
But it throws a 'System.Net.Mail.SmtpException' in System.Net.Mail.dll in client.Send(mailMessage); and i have no idea why. I've been searching for an answer for a days...
Can someone please help me understand whats going on ? Am i missing something ?

Regarding the exception that you are getting, you have to enable Less Secure Sign-In (or Less secure app access) in your google account.
After sign into google account, go to:
https://www.google.com/settings/security/lesssecureapps
or
https://myaccount.google.com/lesssecureapps
and enable the option. Once you do this step, you should be able to send e-mails.

Related

Unable to send mail from bot integrated with slack

I have a bot made in framework v4 using c#.The bot send a email to admin if doesn't able to fetch answer from qna maker.It completely working fine on local emulator, i am able to the mail but when published over slack the bot throw a error.
Here is code
private async Task ProcessSampleQnAAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var results = await _botServices.SampleQnA.GetAnswersAsync(stepContext.Context);
if (results.Any())
{
await stepContext.Context.SendActivityAsync(MessageFactory.Text(results.First().Answer), cancellationToken);
}
else
{
var question = stepContext.Context.Activity.Text;
await stepContext.Context.SendActivityAsync(MessageFactory.Text(_configuration["DefaultAnswer"]), cancellationToken);
string mailbody = "<h4><b>Hi Admin , following question was not answered from bot : </b> </h4>" + question;
Common objCommon = new Common(_configuration);
objCommon.SendEmail(_configuration["EmailSubject_UnAnswerQuestion"], mailbody);
}
}
appsetting.json
"AdminEmailAddress": "****#****.com", //to Email Address
"FromEmailAddress": "******#gmail.com", // From email address
"SMTP_Host": "smtp.gmail.com", // SMTP client Host Name
"SMTP_Port": "587", // SMTP port number
"SMTP_UserName": "****#gmail.com", // email server user name (Email server
network credentials)
"SMTP_Password": "******", // email server password (Email server network
credentials)
"EmailSubject_UnAnswerQuestion": "Question whose answer not found", //
Subject string for un- answere question email.
"DefaultAnswer": "Sorry, could not find an answer in the Q and A system.", //
default answere if answere not found in QnA.
"DelayTimeInSeconds": "60" // Feed back dely time in seconds.
Common logic of smtp
public class Common
{
private readonly IConfiguration _configuration;
public Common(IConfiguration configuration)
{
_configuration = configuration;
}
public bool SendEmail(string subject, string mailbody)
{
string to = _configuration["AdminEmailAddress"]; //To address
string from = _configuration["FromEmailAddress"]; //From address
MailMessage message = new MailMessage(from, to);
message.Subject = subject;
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient(_configuration["SMTP_Host"],
int.Parse(_configuration["SMTP_Port"])); //Gmail smtp
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential(_configuration["SMTP_UserName"],
_configuration["SMTP_Password"]);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
return true;
}catch (Exception ex)
{
throw ex;
}}

C# Smtp.Send not working for specific email address

I haven't had any problems with this code except for one user's email address (everyone has the same "#OurCompany" domain name).
I have sent an email to him through Outlook and it went through fine. There are no exceptions being thrown when the code is run, but our SysAdmin says the emails I tried to send aren't even hitting email the server.
public static void SendEmail(string sTo, string sSubject, string sBody)
{
using (MailMessage message = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["FromUser"], "User"), new MailAddress(sTo))
{
Subject = sSubject,
Body = sBody
})
{
using (var client = new SmtpClient(ConfigurationManager.AppSettings["SMTPGridName"]))
{
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailCredential"],
ConfigurationManager.AppSettings["EmailPassword"]);
client.EnableSsl = true;
client.Send(message);
}
}
}
here is a simple method that can save you a lot of headache
public static void SendEmail(string sTo, string subject, string body)
{
var Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
using (var client = new SmtpClient(Your EmailHost, Port))
using (var message = new MailMessage()
{
From = new MailAddress(FromEmail),
Subject = subject,
Body = body
})
{
message.To.Add(sTo);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailCredential"],
ConfigurationManager.AppSettings["EmailPassword"]);
client.EnableSsl = true;
client.Send(message);
};
}
It turned out the emails were being dropped by SendGrid before it got to our email server for reason "Bounced Address." The SysAdmin thinks the email server might have been down at one point which caused the email address to be added to a "does not exist" list. The address was removed from the list and it works now.
Thanks for the suggestions

How to pass parameters into an HTML email template from C# Windows application to Send an email

Hi I need to send an email using template in c# windows application . I had created a template but i am unable to pass the parameters through the html template. Here is the template which i am using.
For this HTML Template i am calling this in my windows application and sending through gmail smtp. I am able to send the mail but unable to pass the parameters into it. Please Help me out.Here is the code where i am calling in my windows application
try
{
using (StreamReader reader = File.OpenText("H:\\Visitor Management_Project\\Visitor Management_Project\\Visitor Management_Project\\EmailTemplate.htm"))
{
SmtpClient SmtpServer = new SmtpClient("173.194.67.108", 587);
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Credentials = new System.Net.NetworkCredential("ambarishkesavarapu#gmail.com", "*******");
//SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
message = new MailMessage();
message.Subject = "Visitor Arrived";
//message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = "EmailTemplate.htm";
//message.BodyEncoding = System.Text.Encoding.UTF8;
message.From = new MailAddress("ambarishkesavarapu#gmail.com");
message.To.Add(lblCPEmail.Text);
message.Priority = MailPriority.High;
message.Body = reader.ReadToEnd();
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpServer.Send(message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How to add Parameters into HTML Template where i am getting all the parameters of that in the same page in Textboxes. Please help me out
I think you already discovered the answer yourself, but I will keep posting the answer instead.
In case you are using Windows Forms and not Windows Presentation Forms (The different only the design part and many new features that does not have on Windows Forms), what I have done is like this (to send email):
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
May this answer would help you.
Cheers!

Sending email with smtp.secureserver.net with C# and GoDaddy

this is driving me absolutely crazy. I am trying to send an email through a web service written in C# through GoDaddy's servers (smtp.secureserver.net) but for some reason it's not working. Here's my code:
public static void SendMessage(string mailFrom, string mailFromDisplayName, string[] mailTo, string[] mailCc, string subject, string body)
{
try
{
using (SmtpClient client = new SmtpClient("smtpout.secureserver.net"))
{
client.Credentials = new NetworkCredential("myemail#mydomain.com", "mypassword");
client.EnableSsl = true;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
string to = mailTo != null ? string.Join(",", mailTo) : null;
string cc = mailCc != null ? string.Join(",", mailCc) : null;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(mailFrom, mailFromDisplayName);
mail.To.Add(to);
if (cc != null)
{
mail.CC.Add(cc);
}
mail.Subject = subject;
mail.Body = body.Replace(Environment.NewLine, "<BR>");
mail.IsBodyHtml = true;
client.Send(mail);
}
}
catch (Exception ex)
{
// exception handling
}
}
string[] mailTo = { "mytestaddress#gmail.com" };
SendMessage("myemail#mydomain.com", "Test Email", mailTo, null, "Secure Server Test", "Testing... Sent at: " + DateTime.Now);
GOT IT!!! Need to remove the line "client.EnableSsl = true;" because godaddy does not accept secure connections.
I had a similar issue. In my case setting the value of client object's .Port public property was the problem.
Right now, I am not setting that value at all and emails arrive quickly, even with attachments.

Sending an email via Google Apps SMTP Server c#

I am currently developing an application in C# using WPF.
I need the program to be able to send an email to the users email account. The email needs to be sent through my own SMTP server which is using the free Google Apps version for email.
I have put the following code in order to send the message.
try
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 465;
smtpClient.Credentials = new NetworkCredential("myusername", "mypassword");
smtpClient.EnableSsl = true;
MailMessage message = new MailMessage();
message.To.Add(getEmail());
message.Subject = "Password Manager Sync Account Created";
message.From = new MailAddress("username#domain.com");
message.Body = "My Email message"
smtpClient.Send(message);
}
catch (Exception ex)
{
MessageBox.Show("Error Occurred" + ex.Message, "Email Failed", MessageBoxButton.OK, MessageBoxImage.Error);
However, when this code runs it instead just displays an error to say that the operation timed out.
What could be wrong with this?
I have a program that uses SMTP and it goes through port 587 on gmail. Try that.
Here is some code that works for me (forgot where I found it):
public class GmailService : IEmailService
{
private static int _port = 465;
private readonly string _accountName;
private readonly string _password;
public GmailService(string accountName, string password)
{
_accountName = accountName;
_password = password;
}
public void Send(string from, string to, string subject, string body, bool isHtml)
{
Send(from, to, subject, body, isHtml, null);
}
public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
System.Web.Mail.MailMessage mailMessage = new System.Web.Mail.MailMessage
{
From = from,
To = to,
Subject = subject,
Body = body,
BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
};
// Add attachments
if (attachments != null)
{
for (int i = 0; i < attachments.Length; i++)
{
mailMessage.Attachments.Add(new Attachment(attachments[i]));
}
}
// Authenticate
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
// Username for gmail - email#domain.com for email for Google Apps
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
// Password for gmail account
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
// Google says to use 465 or 587. I don't get an answer on 587 and 465 works - YMMV
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
// STARTTLS
mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
// assign outgoing gmail server
SmtpMail.SmtpServer = "smtp.gmail.com";
SmtpMail.Send(mailMessage);
}
}
accountName is something like 'bobcravens#yourserver.com'
password is the password for that account.
Hope this gets you started.
Bob

Categories