BCC email address exception handling in task that sends out email - c#

I setup a task to send an Email asynchronously and trying to handle exception against an Email Address that has been failed for sending an email. It successfully log out the exception but I wonder if I am able to log out the Email Address from Bcc list for which causes the exception to occur. Below is my code, any suggestion on this would be helpful
public void SendEmail(string from, string copyToSender, List<string> bccRecipient, string subject, string body, SmtpSection smtpSection)
{
var context = HttpContext.Current;
if (smtpSection != null)
{
Task.Factory.StartNew(() =>
{
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(from, smtpSection.Network.TargetName);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
myMailMessage = mailMessage;
//send emails to which to Bcc'd including the From Person Email
myMailMessage.Bcc.Add(copyToSender);
foreach (var r in bccRecipient)
{
myMailMessage.Bcc.Add(r);
}
//incorrect email address added to log out the exception against it
myMailMessage.Bcc.Add("foo");
using (var client = new SmtpClient())
{
client.Host = smtpSection.Network.Host;
client.EnableSsl = smtpSection.Network.EnableSsl;
client.Port = Convert.ToInt32(smtpSection.Network.Port);
client.Credentials = new NetworkCredential(smtpSection.Network.UserName,
smtpSection.Network.Password);
client.Send(mailMessage);
}
}).ContinueWith(tsk =>
{
var recipientEmail=//how to figure this out??
//something broke
var flattened = tsk.Exception.Flatten();
flattened.Handle(ex =>
{
_mailLogger.LogError
(recipientEmail, context.Request.UrlReferrer.OriginalString, ex.Message);
return true;
});
}, TaskContinuationOptions.OnlyOnFaulted); ;
}
}

Related

SMTP Email and ERR_CONNECTION_RESET Error in Angular Project

Hi when i use the below code in angular api project my requests are not getting saved and i am gettign this following error. And when i comment the code to send mail everything is working fine
ERROR in console
polyfills POST net::ERR_CONNECTION_RESET
And code to send mail
public async Task SendEmail(string email, string subject, string firstName, string contact)
{
try
{
string message = BuildMessageBody(firstName, email, contact);
using (var client = new SmtpClient())
{
var networkCredential = new NetworkCredential
{
UserName = _configuration["Email:Email"],
Password = _configuration["Email:Password"]
};
client.UseDefaultCredentials = false;
client.Credentials = networkCredential;
client.Host = _configuration["Email:Host"];
client.Port = int.Parse(_configuration["Email:Port"]);
client.EnableSsl = true;
using (var emailMessage = new MailMessage())
{
emailMessage.To.Add(new MailAddress(email));
emailMessage.CC.Add(new MailAddress("my cc adddress"));
emailMessage.From = new MailAddress(_configuration["Email:Email"]);
emailMessage.Subject = subject;
emailMessage.Body = message;
emailMessage.IsBodyHtml = true;
emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
emailMessage.SubjectEncoding = System.Text.Encoding.Default;
emailMessage.ReplyToList.Add(new MailAddress(_configuration["Email:Email"]));
client.SendCompleted += (s, e) => {
client.Dispose();
emailMessage.Dispose();
};
await client.SendMailAsync(emailMessage);
}
}
await Task.CompletedTask;
}
catch (Exception ex)
{
_appLogger.CreateLog("SendEmail - " + ex.Message);
}
}
Any idea why this behaviour???

Asynchronous code to send email notification fails to send email occasionally

My web application in production sometimes fails to send an order email notification. I have never experienced the issue in the test environment.
I do not understand why it is behaving like this way. Could you please guide me on what is causing the issue?
Below is my code:
public async Task SendEmail(int alertID, string body, string subject, List<string> ccemailToUserList)
{
try
{
using (var dbcontext = new MyDbContext())
{
List<string> emailRecipients = new List<string>();
Alert emailAlert = new Alert();
emailAlert = dbcontext.Alerts.FirstOrDefault(x => x.ID == alertID);
body = body.Replace("[[ordertype]]", emailAlert.Description);
MailMessage mail = new MailMessage();
var mailFrom = ConfigurationManager.AppSettings["SMTPFrom"].ToString();
mail.From = new MailAddress(mailFrom);
mail.To.Add(emailAlert.Recipients);
foreach (var ccEmail in ccemailToUserList)
{
mail.CC.Add(ccEmail);
}
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
mail.Subject = emailAlert.Description+ " - " + subject;
mail.Body = body;
mail.IsBodyHtml = true;
await client.SendMailAsync(mail);
}
}
catch (Exception ex)
{
ErrorService.LogError(ex, "Email Error");
}
}

It doesn't go into catch when I send wrong (doesn't exist) mail by C#

I can send mails with no problem. But also my code should control that if the mail address is correct. If not it should go into the catch block. But it doesn't go into the catch. So it seems like all the mails I am trying send is being sent even the mail addresses aren't correct.enter code here
Because of that I can't figure out if all the mails are sent to the mail addresses
using (var smtp = new SmtpClient())
{
smtp.Host = emailSetting.Host;
smtp.EnableSsl = emailSetting.EnableSSL ?? true;
smtp.Port = Convert.ToInt32(emailSetting.Port);
smtp.UseDefaultCredentials = false;
var credentials = new NetworkCredential
{
UserName = emailSetting.EmailAdress,
Password = emailSetting.Password
};
smtp.Credentials = credentials;
int sendMailCount = 0;
var x = serviceEmail.GetQueueEmail();
foreach (var email in x.ToList())
{
using (var mailMessage = new MailMessage())
{
try
{
mailMessage.From = new MailAddress(emailSetting.EmailAdress, emailSetting.FromDisplayName);
mailMessage.To.Add("xyz#hotmail.com");//wrong email address
mailMessage.Subject = email.Subject;
mailMessage.IsBodyHtml = true;
mailMessage.Body = email.Body;
email.Status = EmailStatus.SEND;
smtp.Send(mailMessage);
}
catch (Exception ex)
{
email.Status = EmailStatus.FAILED;
continue;
}
}
}

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.

How to send email to multiple address using System.Net.Mail

I have smtp email functionality. it works for single address but has problem in multiple address.
i am passing multiple addresses using following line of code.
MailAddress to = new MailAddress("abc#gmail.com,xyz#gmail.com");
Please let me know the problem as i am not getting any error.
MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
To is a MailAddressCollection, so you can add how many addresses you need.
If you need a display name, try this:
MailAddress to = new MailAddress(
String.Format("{0} <{1}>",display_name, address));
try this..
using System;
using System.Net.Mail;
public class Test
{
public static void Main()
{
SmtpClient client = new SmtpClient("smtphost", 25);
MailMessage msg = new MailMessage("x#y.com", "a#b.com,c#d.com");
msg.Subject = "sdfdsf";
msg.Body = "sdfsdfdsfd";
client.UseDefaultCredentials = true;
client.Send(msg);
}
}
I think you can use this code in order to have List of outgoing Addresses having a display Name (also different):
//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("myaccount#myaccount.com", "my display name");
String fromPassword = "password";
//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();
//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
TO_addressList.Add(mytoAddress);
}
//4.The Email Body Message
String body = bodymsg;
//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 30000
};
//6.Complete the message and SEND the email:
using (var message = new MailMessage()
{
From = fromAddress,
Subject = subject,
Body = body,
})
{
message.To.Add(TO_addressList.ToString());
smtp.Send(message);
}
StewieFG suggestion is valid but if you want to add the recipient name use this, with what Marco has posted above but is email address first and display name second:
msg.To.Add(new MailAddress("your#email1.com","Your name 1"));
msg.To.Add(new MailAddress("your#email2.com","Your name 2"));
My code to solve this problem:
private void sendMail()
{
//This list can be a parameter of metothd
List<MailAddress> lst = new List<MailAddress>();
lst.Add(new MailAddress("mouse#xxxx.com"));
lst.Add(new MailAddress("duck#xxxx.com"));
lst.Add(new MailAddress("goose#xxxx.com"));
lst.Add(new MailAddress("wolf#xxxx.com"));
try
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "10.15.130.28"; //or SMTP name
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("from#email.com", "password");
objeto_mail.From = new MailAddress("from#email.com");
//add each email adress
foreach (MailAddress m in lst)
{
objeto_mail.To.Add(m);
}
objeto_mail.Subject = "Sending mail test";
objeto_mail.Body = "Functional test for automatic mail :-)";
client.Send(objeto_mail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
namespace WebForms.Code.Logging {
public class ObserverLogToEmail: ILog {
private string from;
private string to;
private string subject;
private string body;
private SmtpClient smtpClient;
private MailMessage mailMessage;
private MailPriority mailPriority;
private MailAddressCollection mailAddressCollection;
private MailAddress fromMailAddress, toMailAddress;
public MailAddressCollection toMailAddressCollection {
get;
set;
}
public MailAddressCollection ccMailAddressCollection {
get;
set;
}
public MailAddressCollection bccMailAddressCollection {
get;
set;
}
public ObserverLogToEmail(string from, string to, string subject, string body, SmtpClient smtpClient) {
this.from = from;
this.to = to;
this.subject = subject;
this.body = body;
this.smtpClient = smtpClient;
}
public ObserverLogToEmail(MailAddress fromMailAddress, MailAddress toMailAddress,
string subject, string content, SmtpClient smtpClient) {
try {
this.fromMailAddress = fromMailAddress;
this.toMailAddress = toMailAddress;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
mailAddressCollection = new MailAddressCollection();
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}
public ObserverLogToEmail(MailAddressCollection fromMailAddressCollection,
MailAddressCollection toMailAddressCollection,
string subject, string content, SmtpClient smtpClient) {
try {
this.toMailAddressCollection = toMailAddressCollection;
this.ccMailAddressCollection = ccMailAddressCollection;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}
public ObserverLogToEmail(MailAddressCollection toMailAddressCollection,
MailAddressCollection ccMailAddressCollection,
MailAddressCollection bccMailAddressCollection,
string subject, string content, SmtpClient smtpClient) {
try {
this.toMailAddressCollection = toMailAddressCollection;
this.ccMailAddressCollection = ccMailAddressCollection;
this.bccMailAddressCollection = bccMailAddressCollection;
this.subject = subject;
this.body = content;
this.smtpClient = smtpClient;
} catch {
throw new SmtpException(SmtpStatusCode.CommandNotImplemented);
}
}#region ILog Members
// sends a log request via email.
// actual email 'Send' calls are commented out.
// uncomment if you have the proper email privileges.
public void Log(object sender, LogEventArgs e) {
string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
fromMailAddress = new MailAddress("", "HaNN", System.Text.Encoding.UTF8);
toMailAddress = new MailAddress("", "XXX", System.Text.Encoding.UTF8);
mailMessage = new MailMessage(fromMailAddress, toMailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
// commented out for now. you need privileges to send email.
// _smtpClient.Send(from, to, subject, body);
smtpClient.Send(mailMessage);
}
public void LogAllEmails(object sender, LogEventArgs e) {
try {
string message = "[" + e.Date.ToString() + "] " + e.SeverityString + ": " + e.Message;
mailMessage = new MailMessage();
mailMessage.Subject = subject;
mailMessage.Body = body;
foreach(MailAddress toMailAddress in toMailAddressCollection) {
mailMessage.To.Add(toMailAddress);
}
foreach(MailAddress ccMailAddress in ccMailAddressCollection) {
mailMessage.CC.Add(ccMailAddress);
}
foreach(MailAddress bccMailAddress in bccMailAddressCollection) {
mailMessage.Bcc.Add(bccMailAddress);
}
if (smtpClient == null) {
var smtp = new SmtpClient {
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("yourEmailAddress", "yourPassword"),
Timeout = 30000
};
} else smtpClient.SendAsync(mailMessage, null);
} catch (Exception) {
throw;
}
}
}
I'm used "for" operator.
try
{
string s = textBox2.Text;
string[] f = s.Split(',');
for (int i = 0; i < f.Length; i++)
{
MailMessage message = new MailMessage(); // Create instance of message
message.To.Add(f[i]); // Add receiver
message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
message.Subject = label3.Text; // Set subject
message.Body = richTextBox1.Text; // Set body of message
client.Send(message); // Send the message
message = null; // Clean up
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
string[] MultiEmails = email.Split(',');
foreach (string ToEmail in MultiEmails)
{
message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
}
MailAddress fromAddress = new MailAddress (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
Host = host, Port = port,
enabHost = "smtp.gmail.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = true,
Credentials = new NetworkCredentials (fromMail, password)
};
smtp.send(message);

Categories