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");
}
}
Related
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???
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;
}
}
}
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); ;
}
}
I am trying to send Email who are listed in my Userprofiles table and i have also added 2 columns like PhoneNo and Email. And also added values in this table. My wish is to send email these listed persons at a time. Now it is sending only one mail at a time. I have tried this code but it is not working. Please Help..
public ActionResult SendEmail(string address, string subject, string message)
{
if (ModelState.IsValid)
{
var v = (from e in db.todaySalesReport()
select e).SingleOrDefault();
var ctx = new UsersContext();
string from = "";
foreach (var i in ctx.UserProfiles.ToList())
{
address = i.Email;
//MailAddress addr = new MailAddress();
using (MailMessage mail = new MailMessage(from, address))
{
mail.To.Add(i.Email);
mail.Subject = "Total Sales Report for today";
mail.Body = "Total sales" + v.qty.ToString() + "Peices.";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "");
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
return View("Index", address);
}
}
}
else
{
return View();
}
return RedirectToAction("Index");
}
This is because you are returning your view inside your foreach loop. Take this code out of the foreach loop:
return View("Index", address);
It should be like this:
if (ModelState.IsValid)
{
var v = (from e in db.todaySalesReport()
select e).SingleOrDefault();
var ctx = new UsersContext();
string from = "";
foreach (var i in ctx.UserProfiles.ToList())
{
address = i.Email;
//MailAddress addr = new MailAddress();
using (MailMessage mail = new MailMessage(from, address))
{
mail.To.Add(i.Email);
mail.Subject = "Total Sales Report for today";
mail.Body = "Total sales" + v.qty.ToString() + "Peices.";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "");
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
}
}
return View("Index", address);
}
You have this
return View("Index", address);
dangling at the end of your loop. Move it out of the loop and it should be fine.
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.