I have this method that will send Email to people according to my SQL SELECT, it works like this:
using (SqlCommand cmd = new SqlCommand("SELECT TITLE, RECIPIENT, SENDER FROM DAY2, CADUSER WHERE CADUSER.ID = ID_CADUSER", con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
sb.AppendLine(reader["TITLE"].ToString());
st.AppendLine(reader["RECIPIENT"].ToString());
se.AppendLine(reader["SENDER"].ToString());
}
}
SmtpClient smtpClient = new SmtpClient("mysmtp.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("______", "______");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
MailMessage mailMessage = new MailMessage(se.ToString(), st.ToString());
mailMessage.Subject = "New Documents";
mailMessage.Body = "The documents are: \n" + sb.ToString();
smtpClient.Send(mailMessage);
}
catch (ArgumentException)
{
}
The problem is that when I have more than 1 sender or recipient, It won't work because AppendLine command will join every result from my select in just one line like this: test#gmail.comtest2#gmail.com making it impossible to send.
How can I separate one Email address by one to correct this issue? Thought about making a While routine but I don't know.
In brief, try this:
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
List<string> To = new List<string>();
To.Add("email1#gmail.com");
To.Add("email1#gmail.com");
foreach (var item in To)
{
mail.To.Add(to);
}
SmtpServer.Send(mail);
Check this out, there are many attributes to help you.
I hope this helps
Related
hi im geting my email list from db in a listbox(email_c) and i need to send to all
this is the error that i get with my code
System.FormatException: 'The specified string is not in the form required for an e-mail address.'
login = new NetworkCredential(txtuser.Text, txtPassword.Text);
client1 = new SmtpClient(txtSmtp.Text);
client1.Port = Convert.ToInt32(txtPort.Text);
client1.Credentials = login;
string emails = email_c.GetItemText(email_c.Items);
msg = new MailMessage { From = new MailAddress(txtuser.Text + txtSmtp.Text.Replace("smtp.", "#"), "Sesizare", Encoding.UTF8) };
msg.To.Add(new MailAddress(emails));
if (!string.IsNullOrEmpty(txtCC.Text))
msg.To.Add(new MailAddress(txtCC.Text));
msg.Subject = txtSubject.Text;
msg.Body = "Abonamentul dumneavoastra a fost activat";
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client1.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userstate = "Ttimite...";
client1.SendAsync(msg, userstate);
The MailAddress does represent the address of an electronic mail sender or recipient. That means it is one single email.
Because of that, instead of writing all the email string into a single string variable you should iterate over the items in the listbox and add each of them individually to the MailMessage. Something like this:
foreach (var email in email_c.Items)
{
msg.To.Add(new MailAddress(email.ToString()));
}
I want to send emails to multiple recipients in ASP.NET MVC and I find it challenging. My code only sends to the first email address on the list, but I want to send to about 400 recipients at once. These recipients' addresses are stored in an SQL Server database. Here is my code
[HttpPost]
[ValidateInput(false)]
public ActionResult SendBulkEmail(EmailAddress ea, HttpPostedFileBase postedFile)
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["senderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["senderPassword"].ToString();
if (ModelState.IsValid)
{
SqlDataReader reader;
using (SqlConnection cs = new SqlConnection(conn))
{
cs.Open();
SqlCommand cmd = new SqlCommand("SELECT email_address FROM Newsletter", cs);
ArrayList emailArray = new ArrayList();
reader = cmd.ExecuteReader();
myFunctions m = new myFunctions();
var emailList = m.LoadEmails();
var emails = new List<AllEmailAddresses>();
while (reader.Read())
{
emails.Add(new AllEmailAddresses
{
EmailAddress = Convert.ToString(reader["email_address"])
});
}
foreach (AllEmailAddresses email in emailList)
{
try
{
SmtpClient client = new SmtpClient("mail.chijiokechinedu.com", 25);
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
//MailMessage mailMessage = new MailMessage(senderEmail, email.EmailAddress, ea.EmailSubjest, ea.EmailBody);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(senderEmail);
mailMessage.To.Add(new MailAddress(email.EmailAddress));
mailMessage.Subject = ea.EmailSubjest;
mailMessage.Body = ea.EmailBody;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
if (postedFile != null)
{
string fileName = Path.GetFileName(postedFile.FileName);
mailMessage.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
}
client.Send(mailMessage);
return RedirectToAction("EmailSentSuccessfully", "Home");
}
catch (Exception)
{
throw;
}
}
}
}
else
{
ModelState.AddModelError("", "email failed to send!");
}
return View(ea);
}
You need to move the redirect (return RedirectToAction("EmailSentSuccessfully", "Home");) to the bottom of that function as at the moment as soon as you send the first email it will redirect
[HttpPost]
[ValidateInput(false)]
public ActionResult SendBulkEmail(EmailAddress ea, HttpPostedFileBase postedFile)
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["senderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["senderPassword"].ToString();
if (ModelState.IsValid)
{
SqlDataReader reader;
using (SqlConnection cs = new SqlConnection(conn))
{
cs.Open();
SqlCommand cmd = new SqlCommand("SELECT email_address FROM Newsletter", cs);
ArrayList emailArray = new ArrayList();
reader = cmd.ExecuteReader();
myFunctions m = new myFunctions();
var emailList = m.LoadEmails();
var emails = new List<AllEmailAddresses>();
while (reader.Read())
{
emails.Add(new AllEmailAddresses
{
EmailAddress = Convert.ToString(reader["email_address"])
});
}
foreach (AllEmailAddresses email in emailList)
{
SmtpClient client = new SmtpClient("mail.chijiokechinedu.com", 25);
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
//MailMessage mailMessage = new MailMessage(senderEmail, email.EmailAddress, ea.EmailSubjest, ea.EmailBody);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(senderEmail);
mailMessage.To.Add(new MailAddress(email.EmailAddress));
mailMessage.Subject = ea.EmailSubjest;
mailMessage.Body = ea.EmailBody;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
if (postedFile != null)
{
string fileName = Path.GetFileName(postedFile.FileName);
mailMessage.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
}
client.Send(mailMessage);
}
// ** redirect after sending all the emails
return RedirectToAction("EmailSentSuccessfully", "Home");
}
}
else
{
ModelState.AddModelError("", "email failed to send!");
}
return View(ea);
}
However you might want to remodel your approach and put this on back of a queue due to the following questions:
1) What happends if after 10 emails one fails? what do you do with the rest?
2) This is a fairly long running process, what happends if the connection between the client and the server get segregated?
From the code it looks like you are going to sent the exact same email to everyone?
If that’s the case maybe you should consider using BCC for all your recipients!
That way you only have to send one email. Most Mailservers need some kind of throttling when you bulk sent mail, so the less items the better.
I have the following email function that sends an email to a list of users. I add the users with the method message.To.Add(new MailAddress("UserList#email.com")):
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.To.Add(new MailAddress("UserList#email.com"));
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
But, how can I connect to a SQL-Server Db and get the list of users from a table, instead of from this function? Thanks for the help!
I figured it out myself in the most simple way. I hope this help someone else. Thanks to everybody who responded with positive comments, have the ability to think, and use common sense.
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
SqlCommand cmd = null;
string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
string queryString = #"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
message.To.Add(to);
}
// Passing values to smtp object
smtp.Send(message);
// Call Close when done reading.
reader.Close();
}
}
You could create this utilities.cs file in your current project and paste in the following code and see how much easier it is to read
public class utilities
{
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
}
public static string EmailRecips
{
get
{
return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA#SomeEmail.com|PersonB#SomeEmail.com|Person3#SomeEmail.com"/>
}
}
public static string EmailHost //add and entry in the config file for EmailHost
{
get
{
return ConfigurationManager.AppSettings["EmailHost"];
}
}
public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
{
using (var client = new SmtpClient(utilities.EmailHost, 25))
using (var message = new MailMessage()
{
From = new MailAddress(utilities.FromEmail),
Subject = subject,
Body = body
})
{
//client.EnableSsl = true; //uncomment if you really use SSL
//client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
//client.Credentials = new NetworkCredential(fromAddress, fromPassword);
foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
message.To.Add(address);
client.Send(message);
}
}
}
//if you want to pass a List and join into a single string of Pipe Delimited string to use in the .Split Function then you can change the method signature to take a string and pass in this to the email for example
var emailList = string.Join("|", YourList<T>);
//then the new email function signature would look like this
public static void SendEmail(string subject, string body, string emailList)
//then you would replace the .Split method with this
foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
You can do a lot to optimize and generalize the code below - it's as close to your code as possible while doing what you want. It's up to you to figure out how to connect to your database and get the DataReader.Read(). Try -- if you get stuck, ask something specific.
Using System.Net.Mail
protected void SendMail()
{
Dictionary<string,string> recipients = new Dictionary<string,string>
//--select FirstName, Email form MyClients
//while reader.Read(){
recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
//}
//Mail notification
foreach(KeyValuePair<string,string> kvp in recipients){
MailMessage message = new MailMessage();
message.To.Add(new MailAddress(kvp.Value));
message.Subject = "Hello, "+kvp.Key;
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
} //This bracket was outside the code box
I have the following code for sending an email alert to around 60 users when an extract gets uploaded. It will send to all the accounts if i am running it locally but when I upload it to the server it doesnt send out any emails, not unless its only to one person. I dont have much experience with hosting and server stuff so any help you can give me would be great.
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Connection String (SendEmail)
string SendEmail = ConfigurationManager.ConnectionStrings["Sendmail"].ConnectionString;
SqlDataReader reader;
String SendMessage = "SELECT Name, Position, Email FROM AuthorisedStaff Where Position = 'CM' or Position = 'DHOD' or Position = 'HOD'"; //<---- change position before launch
using (SqlConnection myConnection = new SqlConnection(SendEmail))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(SendMessage, myConnection);
ArrayList emailArray = new ArrayList();
reader = myCommand.ExecuteReader();
var emails = new List<EmailCode>();
while (reader.Read())
{
emails.Add(new EmailCode
{
Email = Convert.ToString(reader["Email"]),
Name = Convert.ToString(reader["Name"]),
Position = Convert.ToString(reader["Position"])
});
}
foreach (EmailCode email in emails)
{
//Email Config
const string username = "roll#test.ac.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.ac.uk", "PTLP"); //address and from name
smtpclient.Host = "omavex011"; //host name for particular email address
smtpclient.Port = 25; //port number for particular email address
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
//change context of message below as appropriate
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Payroll details are now available for checking.</p> ";
//smtpclient.EnableSsl = true;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
}
}
}
As mentioned in my comment this is how you would use a single SmtpClient instance:
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Email Config
const string username = "roll#test.ac.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
smtpclient.Host = "omavex011";
smtpclient.Port = 25;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
string SendEmail = ConfigurationManager.ConnectionStrings["Sendmail"].ConnectionString;
SqlDataReader reader;
String SendMessage = "SELECT Name, Position, Email FROM AuthorisedStaff Where Position = 'CM' or Position = 'DHOD' or Position = 'HOD'"; //<---- change position before launch
using (SqlConnection myConnection = new SqlConnection(SendEmail))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(SendMessage, myConnection);
ArrayList emailArray = new ArrayList();
reader = myCommand.ExecuteReader();
var emails = new List<EmailCode>();
while (reader.Read())
{
emails.Add(new EmailCode { Email = Convert.ToString(reader["Email"]),
Name = Convert.ToString(reader["Name"]),
Position = Convert.ToString(reader["Position"])
});
}
foreach (EmailCode email in emails)
{
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.ac.uk", "PTLP"); //address and from name
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Payroll details are now available for checking.</p> ";
smtpclient.Send(mail);
}
}
smtpclient.Dispose();
}
I'm working with c# in vs 2010, I made a class and method to send mail via smtp, I need
to send the same mail to many users, I made a list whith a query to select in my DB all
mails and not write them in my code, but I get this error message "Attempt to access
a socket not allowed by your access permissions",
and I can't send an email to many users, here is my code:
in "send button"
private void enviar()
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
Enviar_Mail envi_mail = new Enviar_Mail();
List<string> en_mail = envi_mail.SqlSelectMails();
foreach (string mail_bci in en_mail)
{
msg.To.Add(mail_bci);
}
msg.From = new MailAddress("soporte.web#ipsos.com", "AaBb1234",
System.Text.Encoding.UTF8);
msg.Subject = "prueba mails aviso y acusete bci";
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = "saludos";
msg.BodyEncoding = System.Text.Encoding.Unicode;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("soporte.web", "AaBb1234");
client.Port = 25;
client.Host = "smtp0.chile.latam.ipsos";
client.EnableSsl = false;
try
{
client.Send(msg);
}
catch (System.Net.Mail.SmtpException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
in my class:
public List<string> SqlSelectMails()
{
List<string> dir_mails = new List<string>();
string stSql = "select mail_usuario from mail_usuario";
Bd mibd = new Bd();
SqlDataReader sdr = mibd.sqlExecute(stSql);
while (sdr.Read())
{
dir_mails.Add(sdr["mail_usuario"].ToString());
}
return dir_mails;
}
thanks in advance.