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???
Related
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");
}
}
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 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();
}
}
I am trying to send Emails from my custom address to users using C# and googles smtp service. My problem is that when the when the user receives the message it is displayed admin#customDomain.co.uk <myAddress#gmail.com> in the from section of the email.
My problem is that I want the user to see admin#customDomain.co.uk <admin#customDomain.co.uk>. Is this possible using the google service? Or should I look at some other option? If so what?
I have tried the answers on this thread but non worked and I also found this google blog post but I cant work out how it can solve my issue
My Code
string SmtpAddress = "smtp.gmail.com";
int MyPort = 587;
bool enableSSL = true;
string MyPassword = "somePassword";
string MyUsername = "aUsername";
public string EmailFrom = "admin#customDomain.co.uk";
public string Subject = "Test Subject";
public void Send(string body, BL.Customer customer)
{
using (MailMessage message = new MailMessage())
{
message.To.Add(new MailAddress(customer.EmailAddress));
if (!String.IsNullOrEmpty(customer.SCEmailAddress))
{
//message.To.Add(new MailAddress(customer.SCEmailAddress));
}
message.From = new MailAddress(EmailFrom, EmailFrom);
message.Subject = Subject;
message.Body = string.Format(body);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = MyUsername,
Password = MyPassword
};
smtp.Credentials = credential;
smtp.Host = SmtpAddress;
smtp.Port = MyPort;
smtp.EnableSsl = enableSSL;
try
{
smtp.Send(message);
}
catch (SmtpException se)
{
throw se;
}
}
}
}
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); ;
}
}