Sending email in C# - c#

I am working on a page where I have to send an email in C#.
I followed the codes on
http://blogs.msdn.com/b/mariya/archive/2006/06/15/633007.aspx
and came upon this two exceptions
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll. A first chance exception of type
'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Here are the codes I implemented. I can't seem to figure what went wrong.
//Send email notification - removed actual email for this question
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
MailAddress from = new MailAddress("myemail#gmail.com", "My name is here");
MailAddress to = new MailAddress("anotherpersonsemail#gmail.com", "Subject here");
MailMessage message = new MailMessage(from, to);
message.Body = "Thank you";
message.Subject = "Successful submission";
NetworkCredential myCreds = new NetworkCredential("myemail#gmail.com",
"mypassword", "");
client.Credentials = myCreds;
try
{
client.Send(message);
Console.Write(ex.Message.ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}

For sharing purposes, I managed to resolve my problem by enabling access for less secure apps in Gmail.
It works like a charm now! https://www.google.com/settings/security/lesssecureapps
To authenticate SMTP in Outlook, the articles below are very useful too.
http://www.tradebooster.com/web-hosting-articles/how-to-enable-smtp-authentication-in-outlook-2010/
https://www.authsmtp.com/outlook-2010/default-port.html

//bulk Emails using mailkit you have to import it by nuget manager
//set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
// Read Text File
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}

Answer Update 2023
After Google introduced a Two-step verification system in Google Accounts, it's not easy to use Gmail for your own personal usage so to solve this problem, I figured out a way to use Gmail as an email medium to send emails using C#.
The C# code for email service is included here: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Following just the 2-step tutorial from the above link, you can fix your issue in no time.

Related

How do I to use MailMessage to send mail using SendGrid?

I'm trying to send mail using SendGrid but I can't. It always throws an exception that I can't fix.
How do I to fix this issue ?
SendMail
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName){
try{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo) {
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = CustomEmail.SENDGRID_SMTP_SERVER;
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail);
return true;
}catch (SmtpException e){
Debug.WriteLine(e.Message);
return false;
}
}
CustomMail
//SendGrid Configs
public const String SENDGRID_SMTP_SERVER = "smtp.sendgrid.net";
public const int SENDGRID_PORT_587 = 587;
public const String SENDGRID_API_KEY_USERNAME = "apikey"; //myself
public const String SENDGRID_API_KEY_PASSWORD = "SG.xx-xxxxxxxxxxxxxxxxxxxxxxxxx-E";
Exception
Exception thrown: 'System.Net.Mail.SmtpException' in System.dll
Server Answer: Unauthenticated senders not allowed
For sending emails with SendGrid there is v3 API. The NuGet name is SendGrid and the link is here.
This library does not work with System.Net.Mail.MailMessage, it uses SendGrid.Helpers.Mail.SendGridMessage.
This library uses an API key for authorization. You can create one when you log into SendGrid web app, and navigate to Email API -> Integration Guide -> Web API -> C#.
var client = new SendGridClient(apiKey);
var msg = MailHelper.CreateSingleTemplateEmail(from, new EmailAddress(to), templateId, dynamicTemplateData);
try
{
var response = client.SendEmailAsync(msg).Result;
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.Accepted)
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
}
}
catch (WebException exc)
{
throw new WebException(new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(), exc);
}
I think your problem stems from not instantiating the SMTP client with the server in the constructor. Also you should wrap your smtpclient in a using statement so it disposes of it properly, or call dispose once you're finished.
Try this:
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName)
{
try
{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo)
{
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
using(SmtpClient smtp = new SmtpClient(CustomEmail.SENDGRID_SMTP_SERVER)){
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail)
}
}
catch (SmtpException e)
{
Debug.WriteLine(e.Message);
return false;
}
}
If that doesn't work you could try removing the port, enablessl and usedefaultcredentials parameters for the smtp client. I use sendgrid all the time and don't use those options.
To more specifically answer your original question and the cause of your exception, the SendGrid SMTP server probably isn't looking for your account's username and password, but rather your API key. The error seems to indicate your authentication is not successful.
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
To integrate with SendGrids SMTP API:
Create an API Key with at least "Mail" permissions.
Set the server host in your email client or application to smtp.sendgrid.net.
This setting is sometimes referred to as the external SMTP server or the SMTP relay.
Set your username to apikey.
Set your password to the API key generated in step 1.
Set the port to 587.
Using the SendGrid C# library will also simplify this process:
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
// using SendGrid's C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
}
}
}

The specified string is not in the form required for an e-mail address. when sending an email

Trying to send email to multiple recipient using below code gives me this error:
The specified string is not in the form required for an e-mail
address.
string[] email = {"emailone#gmail.com","emailtow#gmail.com"};
using (MailMessage mm = new MailMessage("teset123321#gmail.com", email.ToString()))
{
try
{
mm.Subject = "sub;
mm.Body = "msg";
mm.Body += GetGridviewData(GridView1);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtpout.server.net";
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential("email", "pass");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 80;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
}
Change your using line to this:
using (MailMessage mm = new MailMessage())
Add the from address:
mm.From = new MailAddress("myaddress#gmail.com");
You can loop through your string array of e-mail addresses and add them one by one like this:
string[] email = { "emailone#gmail.com", "emailtwo#gmail.com", "emailthree#gmail.com" };
foreach (string address in email)
{
mm.To.Add(address);
}
Example:
string[] email = { "emailone#gmail.com", "emailtwo#gmail.com", "emailthree#gmail.com" };
using (MailMessage mm = new MailMessage())
{
try
{
mm.From = new MailAddress("myaddress#gmail.com");
foreach (string address in email)
{
mm.To.Add(address);
}
mm.Subject = "sub;
// Other Properties Here
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
}
Presently your code:
new NetworkCredential("email", "pass");
treats "email" as an email address which eventually is not an email address rather a string array which contains the email address.
So you can try like this:
foreach (string add in email)
{
mm.To.Add(new MailAddress(add));
}
I was having this issue while working with SMTP.js but the issues were coming from the whitespace so please try and trim it off when working with emails. I hope this helps someone.

Smtp mail delivered unsuccessfully

I am using Smtp to send mail.A message was sent successfully but it was not delivered. What is the reason behind this.Is this a problem in mailing server?The message sending process is working fine for the last couple of years.The issue came first time.
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
Log.WriteSpecialLog("smtpClient mail sending first try success", "");
}
catch (Exception ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try Failed : " + ee.ToString(), "");
return false;
}
return true;
}
catch (Exception ex)
{
Log.WriteLog("smtpClient mail sending overall failed : " + ex.ToString());
return false;
}
}
A message was sent successfully but it was not delivered
If it was sent successfully from your mailing server then the possible reason of non delivery can be that the mail filter on client blocked it or is delivered in the junk.

Send SMTP mail when an exception occurs

I'd be grateful if someone could tell me if I'm on the right track... Basically, I have a webservice i need to run for my app, I've put it into a try catch, if the try fails I want the catch to send me an email message with the details of the exception.
try
{
// run webservice here
}
catch (Exception ex)
{
string strTo = "scott#...";
string strFrom = "web#...";
string strSubject = "Webservice Not Run";
SmtpMail.SmtpServer = "thepostoffice";
SmtpMail.Send(strFrom, strTo, strSubject, ex.ToString());
}
Yes you are but you'd better wrapp yor exception handler in some kind of logger or use existing ones like Log4Net or NLog.
A quick and easy way to send emails whenever an Exception occurs can be done like this:
SmtpClient Server = new SmtpClient();
Server.Host = ""; //example: smtp.gmail.com
Server.Port = ; //example: 587 if you're using gmail
Server.EnableSsl = true; //If the smtp server requires it
//Server Credentials
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = "youremail#gmail.com";
credentials.Password = "your password here";
//assign the credential details to server
Server.Credentials = credentials;
//create sender's address
MailAddress sender = new MailAddress("Sender email address", "sender name");
//create receiver's address
MailAddress receiver = new MailAddress("receiver email address", "receiver name");
MailMessage message = new MailMessage(sender, receiver);
message.Subject = "Your Subject";
message.Body = ex.ToString();
//send the email
Server.Send(message);
Yes this the right way, if you don't want to use any logger tool.You can create function SendMail(string Exceptioin) to one of the your common class and than call this function from each catch block

Can't send smtp email from network using C#, asp.net website

I have my code here, it works fine from my home, where my user is administrator, and I am connected to internet via a cable network.
But, problem is when I try this code from my work place, it does not work. Shows error:
"unable to connect to the remote server"
From a different machine in the same network:
"A socket operation was attempted to an unreachable network 209.xxx.xx.52:25"
I checked with our network admin, and he assured me that all the mail ports are open [25,110, and other ports for gmail].
Then, I logged in with administrative privilege, there was a little improvement, it did not show any error, but the actual email was never received.
Please note that, the code was tested from development environment, visual studio 2005 and 2008.
Any suggestion will be much appreciated.
Thanks in advance
try
{
MailMessage mail_message = new MailMessage("xxxxx#y7mail.com", txtToEmail.Text, txtSubject.Text, txtBody.Text);
SmtpClient mail_client = new SmtpClient("SMTP.y7mail.com");
NetworkCredential Authentic = new NetworkCredential("xxxxx#y7mail.com", "xxxxx");
mail_client.UseDefaultCredentials = true;
mail_client.Credentials = Authentic;
mail_message.IsBodyHtml = true;
mail_message.Priority = MailPriority.High;
try
{
mail_client.Send(mail_message);
lblStatus.Text = "Mail Sent Successfully";
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message;
}
}
catch (Exception ex)
{
lblStatus.Text = "Mail Sending Failed\r\n" + ex.Message;
}
Here is some sample code that works for me and talks to a gmail server
private void SendEmail(string from, string to, string subject, string body)
{
MailMessage mail = new MailMessage(new MailAddress(from), new MailAddress(to));
mail.Subject = subject;
mail.Body = body;
SmtpClient smtpMail = new SmtpClient("smtp.gmail.com");
smtpMail.Port = 587;
smtpMail.EnableSsl = true;
smtpMail.Credentials = new NetworkCredential("xxx#gmail.com", "xxx");
// and then send the mail
smtpMail.Send(mail);
}
Try setting UseDefaultCredentials to false.
Also try switching SSL on for y7mail
mail_client.EnableSSL = true;
Source - http://help.yahoo.com/l/au/yahoo7/edit/registration/registration-488246.html
private void SendEmail(string from, string to, string subject, string body)
{
MailMessage mail = new MailMessage(new MailAddress(from), new MailAddress(to));
mail.Subject = subject;
mail.Body = body;
SmtpClient smtpMail = new SmtpClient("smtp.gmail.com");
smtpMail.Port = 587;
smtpMail.EnableSsl = true;
smtpMail.Credentials = new NetworkCredential("xxx#gmail.com", "xxx");
// and then send the mail
smtpMail.Send(mail);
}
This is the best answer for System.Exception Problem. Totally verified, you need to provide username and password at network credentials. Also try to give this solution to other sites.

Categories

Resources