Send Notification Mail to Multiple users suing SMTP each having different Message - c#

I have to send notification to a array of users in the to-recipients and each user has a different message body which is stored in another array.
When i try to use multiple calls to SMTP.send() to send the notification to each user (i tried testing for 2 users) one by one with their respective message body, I get Exception like
"{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.1.11.16:25"}".
where as it works fine in the case when make a single SMTP.send call where i have ';' separated recipients and same message body.
How do I Solve it.
Controller code sending the array of users and message in array.
string[] emailBodyList = FormatedEmail.ToArray();
string[] emailIdList = emailIDs.ToArray(); DMS.Common.Encyptor.NotificationSend(FromEmail, ToEmail, CCEmail, BCCEmail, model.MailSubject, emailBodyList, emailIdList);
In the Encryptor.cs the SMTP method:
public static void NotificationSend(string FromEmail, string ToEmail, string CCEmail, string BCCEmail, string EmailSubject, string[] EmailBody = null, string[] emailID =null)
{
for(int i = 0; i < EmailBody.Length ; i++)
{
string notificationBody = EmailBody[i];
string notificationTo = emailID[i];
EmailSend(FromEmail, notificationTo, null, null, EmailSubject, notificationBody);
}
}
public static void EmailSend(string FromEmail, string ToEmail, string CCEmail, string BCCEmail, string EmailSubject, string EmailBody= null, string emailID = null)
{
var email = new MailMessage();
email.From = new MailAddress(FromEmail);
string[] toemails = ToEmail.Split(';');
foreach (string str in toemails)
{
if (!String.IsNullOrEmpty(str) && str.Contains('#'))
{
email.To.Add(new MailAddress(str.TrimEnd(new char[] { ',' })));
}
}
//email.Headers.Add("Reply-To", "saeed.badar#unibetonrm.com");
// Add CC
if (!String.IsNullOrEmpty(CCEmail))
{
string[] ccemails = CCEmail.Split(';');
foreach (string str in ccemails)
{
if (!String.IsNullOrEmpty(str) && str.Contains('#'))
{
email.CC.Add(new MailAddress(str.TrimEnd(new char[] { ',' })));
}
}
}
// Add BCC
if (!String.IsNullOrEmpty(BCCEmail))
{
string[] bccemails = BCCEmail.Split(';');
foreach (string str in bccemails)
{
if (!String.IsNullOrEmpty(str) && str.Contains('#'))
{
email.Bcc.Add(new MailAddress(str.TrimEnd(new char[] { ',' })));
}
}
}
email.IsBodyHtml = true;
email.Body = EmailBody;
email.Subject = EmailSubject;
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = AppConfig.GetValue("SmtpHost").ToString();
smtpClient.Port = int.Parse(AppConfig.GetValue("SmtpPort").ToString());
//smtpClient.EnableSsl = true;
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
smtpClient.Credentials = new System.Net.NetworkCredential(AppConfig.GetValue("SmtpServerUserName").ToString(), AppConfig.GetValue("SmtpServerPassword").ToString());
smtpClient.Send(email);
}

The error message seems to be saying that the error has nothing to do with the type of emails you are trying to send.
Does your SMTP need your windows credentials to log you in? You seem to be trying to do both. Since you are specifying a username and password, try setting
smtpClient.UseDefaultCredentials = false;
before
smtpClient.Credentials = new System.Net.NetworkCredential(AppConfig.GetValue("SmtpServerUserName").ToString(), AppConfig.GetValue("SmtpServerPassword").ToString());
Also, you need to decide whether you are going to use CredentialCache.DefaultNetworkCredentials or not.
Make sure your firewall isn't blocking the connection to the SMTP server, and that your credentials are correct.

Related

How to exclude or remove a specific e-mail address from a sendEmail function in c#

I'm trying to remove or exclude a couple specific e-mail addresses from the CC e-mail address list. How should I do this? Here is the function:
private void SendEmail(string emailTo, string subject, string body)
{
using (SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SmtpServerAddress"]))
{
MailMessage email = new MailMessage();
email.From = new MailAddress(GetUserEmail());
string emailCc = ConfigurationManager.AppSettings["EmailCc"];
foreach (var item in emailTo.Split(';'))
{
email.To.Add(new MailAddress(item.Trim()));
}
foreach (var item in emailCc.Split(';'))
{
email.CC.Add(new MailAddress(item.Trim()));
}
email.Subject = subject;
email.IsBodyHtml = true;
email.Body = body;
return;
}
}
You put the emails you don't want into an array:
var badEmails = new [] { "a#a.aa", "b#b.bb" }
Then you use LINQ to remove them from the split:
var ccList = emailCc.Split(';').Where(cc => !badEmails.Any(b => cc.IndexOf(b, System.StringComparison.InvariantCultureIgnoreCase) > -1));
Then you add those in ccList to your email
You can try with this if you know email:
foreach (var item in emailCc.Split(';'))
{
if (!new string[] { "bad#gmail.com", "uncle#sam.com", "stack#overflow.com"}.Contains(email))
{
email.CC.Add(new MailAddress(item.Trim()));
}
}
instead of if statement you can use regular expression if you want to exclude some email with specific pattern.

c# - ssis task - Send Mail Failure

I have an ssis package where i try to send email to a list of users via a script task.
I am able to successfully send mail to 1000 users but i get error for 10 of them. I am trying to debug the issue . The email ids does not have any problem though. Please find the code snippet below. Any pointers would be greatly helpful.
private void SendMailMessage(string SendTo, string SendCC, string SendBCC, string From, string Subject, string Body, bool IsBodyHtml, string Server, string FileAttachment)
//private void SendMailMessage(string SendTo, string From, string Subject, string Body, bool IsBodyHtml, string Server)
{
SmtpClient mySmtpClient;
String[] splittedAddresses;
MailMessage htmlMessage;
StringBuilder sbAddresses = new StringBuilder();
//emails in a batch.
int numberOfEmails = 10;
int totalEmails = 0;
//take all the addressess and append them into one whole object.
if (!String.IsNullOrEmpty(SendTo))
{
sbAddresses.Append(SendTo);
}
if (!String.IsNullOrEmpty(SendCC))
{
if (sbAddresses.Length > 0)
{
sbAddresses.Append(String.Format(",{0}", SendCC));
}
else
{
sbAddresses.Append(SendCC);
}
}
if(!String.IsNullOrEmpty(SendBCC))
{
if (sbAddresses.Length > 0)
{
sbAddresses.Append(String.Format(",{0}", SendBCC));
}
else
{
sbAddresses.Append(SendBCC);
}
}
mySmtpClient = new SmtpClient(Server);
splittedAddresses = sbAddresses.ToString().Split(new char [] {','}, StringSplitOptions.RemoveEmptyEntries);
//Send the email in batches of #numberOfEmails
while (totalEmails < splittedAddresses.Length)
{
IEnumerable<String> emailRecipients = splittedAddresses.Skip(totalEmails).Take(numberOfEmails);
CreateMailMessage(From, Subject, Body, IsBodyHtml, FileAttachment, out htmlMessage);
foreach(string email in emailRecipients)
{
htmlMessage.Bcc.Add(new MailAddress(email));
}
mySmtpClient.Send(htmlMessage);
totalEmails += emailRecipients.Count();
}
//mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
}
private static void CreateMailMessage(string From, string Subject, string Body, bool IsBodyHtml, string FileAttachment, out MailMessage htmlMessage)
{
htmlMessage = new MailMessage();
htmlMessage.From = new MailAddress(From);
htmlMessage.Subject = Subject;
htmlMessage.Body = Body;
htmlMessage.IsBodyHtml = IsBodyHtml;
htmlMessage.Attachments.Add(new Attachment(FileAttachment));
}

splitting words from a text box using in asp.net

I m new To ASP.net i want to send mail to multiple people by using one textbox and every email address is separated by ,. Now I want to send mail to multiple people. My code is
public static void SendEmail(string txtTo, string txtSubject, string txtBody, string txtFrom)
{
try
{
MailMessage mailMsg = new MailMessage();
SmtpClient smtp = new SmtpClient("mail.valuesoft.org", 26);
smtp.Credentials = new NetworkCredential("mail#----.org", "#123");
mailMsg.From = new MailAddress(txtFrom);
mailMsg.To.Add(txtTo);
mailMsg.Subject = txtSubject;
mailMsg.Body = txtBody;
mailMsg.IsBodyHtml = true;
smtp.Send(mailMsg);
}
catch { }
}
If you are asking for how to parse a comma seperated list:
string[] recipients = txtTo.Split(',');
foreach (string recipient in recipients)
{
mailMsg.To.Add(recipient );
}

Send Email by WebService

I have developed on Windows Application. Now i need to send an email (attachment feature included) by Web Service. How can i do that?
Also i need to notify the email before 'n' days. ('n' days is a feature controlled by user)
Let me know if any comment.
Thanks.
public bool Send(string toAddress, string subject, string body, bool isHtml, List<string> files)
{
try
{
MailMessage mailMsg = new MailMessage();
mailMsg.To = toAddress;
mailMsg.Headers.Add("From", string.Format("{0} <{1}>", senderName, senderAddress));
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = server;
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = port;
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
if (enableAuth)
{
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = userName;
mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = password;
}
if (enableSsl)
{
mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
}
if (isHtml)
{
mailMsg.BodyFormat = MailFormat.Html;
}
mailMsg.BodyEncoding = Encoding.UTF8;
mailMsg.Subject = subject;
mailMsg.Body = body;
for (int i = 0; i < files.Count; i++)
{
mailMsg.Attachments.Add(new MailAttachment(files[i]));
}
SmtpMail.SmtpServer = server;
SmtpMail.Send(mailMsg);
return true;
}
catch (Exception ex)
{
this.errorMsg = ex.Message;
return false;
}
}
Note that you must use System.Web.Mail for this cod to work.

Unable to send an email to multiple addresses/recipients using C#

I am using the below code, and it only sends one email - I have to send the email to multiple addresses.
For getting more than one email I use:
string connectionString = ConfigurationManager.ConnectionStrings["email_data"].ConnectionString;
OleDbConnection con100 = new OleDbConnection(connectionString);
OleDbCommand cmd100 = new OleDbCommand("select top 3 emails from bulk_tbl", con100);
OleDbDataAdapter da100 = new OleDbDataAdapter(cmd100);
DataSet ds100 = new DataSet();
da100.Fill(ds100);
for (int i = 0; i < ds100.Tables[0].Rows.Count; i++)
//try
{
string all_emails = ds100.Tables[0].Rows[i][0].ToString();
{
string allmail = all_emails + ";";
Session.Add("ad_emails",allmail);
Response.Write(Session["ad_emails"]);
send_mail();
}
}
and for sending the email I use:
string sendto = Session["ad_emails"].ToString();
MailMessage message = new MailMessage("info#abc.com", sendto, "subject", "body");
SmtpClient emailClient = new SmtpClient("mail.smtp.com");
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("abc", "abc");
emailClient.UseDefaultCredentials = true;
emailClient.Credentials = SMTPUserInfo;
emailClient.Send(message);
The problem is that you are supplying a list of addresses separated by semi-colons to the MailMessage constructor when it only takes a string representing a single address:
A String that contains the address of the recipient of the e-mail message.
or possibly a list separated by commas (see below).
Source
To specify multiple addresses you need to use the To property which is a MailAddressCollection, though the examples on these pages don't show it very clearly:
message.To.Add("one#example.com, two#example.com"));
The e-mail addresses to add to the MailAddressCollection. Multiple e-mail addresses must be separated with a comma character (",").
MSDN page
so creating the MailMessage with a comma separated list should work.
This is what worked for me.
(recipients is an Array of Strings)
//Fuse all Receivers
var allRecipients = String.Join(",", recipients);
//Create new mail
var mail = new MailMessage(sender, allRecipients, subject, body);
//Create new SmtpClient
var smtpClient = new SmtpClient(hostname, port);
//Try Sending The mail
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
Log.Error(String.Format("MailAppointment: Could Not Send Mail. Error = {0}",ex), this);
return false;
}
This function validates a comma- or semicolon-separated list of email addresses:
public static bool IsValidEmailString(string emailAddresses)
{
try
{
var addresses = emailAddresses.Split(',', ';')
.Where(a => !string.IsNullOrWhiteSpace(a))
.ToArray();
var reformattedAddresses = string.Join(",", addresses);
var dummyMessage = new System.Net.Mail.MailMessage();
dummyMessage.To.Add(reformattedAddresses);
return true;
}
catch
{
return false;
}
}
To send to multiple recipients I set up my recipient string with a comma as my separator.
string recipient = "foo#bar.com,foo2#bar.com,foo3#bar.com";
Then to add the recipients to the MailMessage object:
string[] emailTo = recipient.Split(',');
for (int i = 0; i < emailTo.GetLength(0); i++)
mailMessageObject.To.Add(emailTo[i]);
This code I use for send multiple mail for to, bcc and cc
MailMessage email = new MailMessage();
Attachment a = new Attachment(attach);
email.From = new MailAddress(from);//De
string[] Direcciones;
char[] deliminadores = { ';' };
//Seleccion de direcciones para el parametro to
Direcciones = to.Split(deliminadores);
foreach (string d in Direcciones)
email.To.Add(new MailAddress(d));//Para
//Seleccion de direcciones para el parametro CC
Direcciones = CC.Split(deliminadores);
foreach (string d in Direcciones)
email.CC.Add(new MailAddress(d));
//Seleccion de direcciones para el parametro Bcc
Direcciones = Bcc.Split(deliminadores);
foreach (string d in Direcciones)
enter code here`email.Bcc.Add(new MailAddress(d));
You are also allowed to pass MailMessage.To.Add()a comma separated list of valid RFC 822 e-mail addresses:
Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>
So the code would be:
message.To.Add("Nathaniel Borenstein <nsb#bellcore.com>, Ned Freed <ned#innosoft.com>");
Note: Any code released into public domain. No attribution required.

Categories

Resources