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.
Related
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.
I am using Sendgrid to send emails with templates that contain multiple variables.
Everything works well when I have only one recipient for an email.
When I have multiple recipients either in To or one in To and one in Cc, the first email is ok but the following have empty strings in the substition tags.
Below is my code :
private bool SendEmail(MailAddress from, string[] to, string template, Dictionary<string, string> keyToReplace, string[] cc = null)
{
var message = new SendGridMessage();
message.From = from;
message.AddTo(to);
if (cc != null && cc.Any())
{
foreach (var ccAddress in cc)
{
message.AddCc(ccAddress);
}
}
message.Subject = " ";
message.Text = string.Empty;
message.Html = "<p></p>";
message.EnableTemplate("<%body%>");
message.EnableTemplateEngine(templateIds[template]);
foreach (var keyValue in keyToReplace)
{
var key = keyValue.Key;
if (!key.StartsWith("#"))
{
key = string.Format("#{0}#", key);
}
var value = keyValue.Value;
if (string.IsNullOrEmpty(keyValue.Value))
{
value = " ";
}
message.AddSubstitution(key, new List<string> { value });
}
var transportWeb = transportFactory(credentials);
transportWeb.Deliver(message);
logger.Info("Mail sent to : " + string.Join(", ", to));
return true;
}
I enventually updated the Sendgrid nuget package from version 5.0.0 to version 9.5.0 and it fixed the issue.
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.
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 );
}
Hello I am developing an outlook Add-on, as part of the work flow it should take the mailItem body and subject, and for each recipient it should change the body of message according to recipient e-mail.
The problem is that it just sends the first e-mail and after Send(); it does not send the e-mail to other recipients
Outlook.Application application = Globals.ThisAddIn.Application;
Outlook.Inspector inspector = application.ActiveInspector();
Outlook.MailItem myMailItem = (Outlook.MailItem)inspector.CurrentItem;
myMailItem.Save();
if (myMailItem != null)
{
myMailItem.Save();
PorceesData(myMailItem);
}
..
..
..
..
private void ProcessData(MailItem oMailItem)
{
Recipients recipients = oMailItem.Recipients;
string Body = oMailItem.Body;
string To = oMailItem.To;
string CC = oMailItem.CC;
string bcc = oMailItem.BCC;
foreach (Recipient r in recipients)
{
if (r.Resolve() == true)
{
string msg = "Hello open the attached file (msg.html);
string address = r.Address;
oMailItem.Body = msg;
oMailItem.To = address;
oMailItem.Subject = "my subject"
foreach (Attachment t in oMailItem.Attachments)
{
t.Delete();
}
oMailItem.Attachments.Add(#"mydirectory");
oMailItem.Send();
}
_MailItem.Send() closes the current inspector. This isn't in the _MailItem.Send documentation, but is the actual Outlook implementation. You should probably come up with another approach. I'd suggest creating a new MailItem instance for each message you wish to send.
You can create a new MailItem using...
Outlook.MailItem eMail = (Outlook.MailItem)
Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
eMail.Subject = subject;
eMail.To = toEmail;
eMail.Body = body;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
After sending to all recipients you can manually close the current inspector using the following (Send() implicitly calls this method)
((Outlook._MailItem)myMailItem).Close(Outlook.OlInspectorClose.olDiscard)