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()));
}
Related
I am trying to send mail with multiple attachment in c# but I am getting this error
A recipient must be specified while sending mail
Here is my code for sending mail with attachment
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
if (fileuploading.HasFile)//Attaching document
{
string FileNamess = fileuploading.PostedFile.FileName;
string FileName = Path.GetFileName(fileuploading.PostedFile.FileName);
message.Attachments.Add(new System.Net.Mail.Attachment(fileuploading.PostedFile.InputStream,FileName));
}
string mailbody = editor.Text;
message.Subject = txtsubject.Text;
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("xxx#mail.com","xxxxx");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
}
catch (Exception ex)
{
throw ex;
}
You have an unused string "to". You need to add this string to recipient list message.To.
To do that refer following snippet;
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
message.To.Add(to); //Add this line to your code
For above example to work, your string to should contain a recipient address in format "xxx#mail.com".
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 am trying to send email with unsubsrible link in my aspx page. But when I check my email id It display only text. There was no link. Here is my code generate a email
string bodyContent = CKEditor1.Text;
string userLink = "http://www.abc.in/Message.aspx?action=rmsb&oldsubuser=";
string footerLink = "</br></br></br>You are receiving this mail because you have subscribed to our newsletter. If you do not wish to receive the mail, Click <a href='" + userLink + "" + ids[i].ToString() + "'>Here</a>";
bodyContent = bodyContent + footerLink;
EmailSend newsletter = new EmailSend();
newsletter.NewsLetterSend(ids[i].ToString(), bodyContent.Replace("'", "''"), txtSubject.Text.Replace("'", "''"));
//EmailSend.SendMailMessage("faredpt#gmail.com", ids[i].ToString(), "", "", txtSubject.Text, bodyContent);
bodyContent = bodyContent.Replace(footerLink, " ");
Here is the code for NewsLetterSend function
public void NewsLetterSend(string getemailAdd, string msgBody, string subject)
{
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("admin#abc.in", "admin#abc.in");
mail.To.Add(getemailAdd.Trim());
//set the content
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = msgBody;
mail.Priority = MailPriority.High;
//set the smtp settings
SmtpClient smtp = new SmtpClient("abc.in");
smtp.EnableSsl = false;
smtp.Credentials = new System.Net.NetworkCredential("admin#abc.in", "i#abc!23#");
//smtp.Port = 3535;
smtp.Port = 25;
//send email
smtp.Send(mail);
return;
}
Now this code is sending email successfully but unable to add link in my email. It show me simple text
Please tell me why this happening
You are replacing the quotation mark in href with two quotation marks!
Invalid statement: bodyContent.Replace("'", "''")
This will render your HTML invalid.
Could you try to replace </br></br></br> with <br/><br/><br/>? Probably because of invalid br tags your email is considered as not valid HTML and links become broken.
May I know how to send email based on gridview column containing email addresses?
I am currently using asp.net and c#. I'm also currently using smtp gmail for the email.
Currently, I had a gridview1 which contain customers (email, name, accountNo) that had bounced cheque, however I wish to send an standard email, to all these customers upon clicking a button. May I know how should i go about it? Their email is stored in database and will be shown on gridview.
private void SendEMail(MailMessage mail)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("#gmail.com", "password");
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
The easiest would be loop through the dataset that you have bound to grid view. But since you have asked about gridview, here is how you can loop through gridview rows
On button_click write this
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//considering 1st column contains email address
//if not, replace it with correct index
email = item.Cells[0].Text;
//code to send email
}
UPDATE 2
Updating my code to use your sendEmail function
public void button_click(object sender, EventArgs e)
{
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//if not, replace it with correct index
email = item.Cells[4].Text;
//code to send email
//reciever email add
MailAddress to = new MailAddress(email);
//sender email address
MailAddress from = new MailAddress("your#email");
MailMessage msg = new MailMessage();
//use reason shown in grid
msg.Subject = item.Cells[3].Text;
//you can similar extract FName, LName, Account number from grid
// and use it in your message body
//Keep your message body like
str email_msg = "Dear {0} {1}, Your cheque for account number {2} bounced because of the reason {3}";
msg = String.Format(email_msg , item.Cells[0].Text,item.Cells[1].Text,item.Cells[2].Text,item.Cells[3].Text);
msg.Body = email_msg ;
msg.From = from;
msg.To.Add(to);
SendEMail(msg);
}
}
try to save the e-mail addresses in an array.
then do a foreach and send the e-mail that are in the array!
example:
CLASS:
public SmtpClient client = new SmtpClient();
public MailMessage msg = new MailMessage();
public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password");
public void Send(string sendTo, string sendFrom, string subject, string body)
{
try
{
//setup SMTP Host Here
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
//convert string to MailAdress
MailAddress to = new MailAddress(sendTo);
MailAddress from = new MailAddress(sendFrom);
//set up message settings
msg.Subject = subject;
msg.Body = body;
msg.From = from;
msg.To.Add(to);
// Send E-mail
client.Send(msg);
}
catch (Exception error)
{
}
}
SENDING E-MAILS: (button_click)
//read the emails from the database and save them in an array.
//count how many are the emails, ex: int countEmails = SqlClass.Function("select emails from table").Rows.Count;
string[] emails = new string[countEmails];
foreach (string item in emails)
{
//send e-mail
callClass.Send(item, emailFrom, subject, body); //you can adapt the class
}
I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}