Sending mails automatically by console application - c#

Create one console application for sending a birthday wishing mail for company employees is here there is send mail code of only one by one employee I try but can't got a multiple emails id from database
Here Code i try it:
class Program
{
static void Main(string[] args)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["EmpDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("SELECT empemail,EmpDOB,empname,Photo,BdayMessage,CC FROM EmpDetails where datepart(day,EmpDOB)= datepart(day,sysdatetime()) and datepart(month,EmpDOB)=datepart(month,sysdatetime())", con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
ArrayList list_emails = new ArrayList();
int i = 0;
string email, Bday;
int diff;
while (reader.Read())
{
email = reader.GetValue(i).ToString();
list_emails.Add(email); //Add email to a arraylist
i = i + 1 - 1;
}
string todaydate = DateTime.Now.ToString("dd/MM");
Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM"); //date converted
diff = DateTime.Compare(DateTime.Today, Convert.ToDateTime(Bday)); //compare cuurent date and date of birthday from database of emplyees with only day and month
//string Bday = Convert.ToDateTime(reader["EmpDOB"]).ToString("dd/MM");
if (diff == 0)
{
//string Email = reader["EmpEmail"].ToString();
string Name = reader["EmpName"].ToString();
string Photo = reader["Photo"].ToString();
string cc = reader["CC"].ToString();
string Bdaymessage = reader["BdayMessage"].ToString();
string body = "<br><b><i><font Size=4 face=Comic Sans MS color= #FF2B9E> Dear</br><br><font Size=4 face=Comic Sans MS color=#FF2B9E>" + Name + "</i></b>" + "<br>" + "<br><img src=" + Photo + "></body></html></body></html>" + "<br><b><font Size=4 face=Comic Sans MS color=#FF2B9E><i>" + Bdaymessage + "</i></b></br> " + "<br><br><br>";
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(Photo, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
av.LinkedResources.Add(inline);
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.AlternateViews.Add(av);
//msg.To.Add(email);
msg.CC.Add(cc);
msg.Subject = " WIsH YoU MaNy MaNY HaPPy Birthday";
msg.From = new System.Net.Mail.MailAddress("example#gmail.com");
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
NetworkCredential NetCrd = new NetworkCredential("eample#gmail.com", "password");
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
reader.Close();
con.Close();
}
else
{
Console.Write("its a earlier date");
}
}
}
}
catch (Exception ex)
{
Console.Write("There is No Birthday" + ex);
}
}
}

You are getting the multiple users form the database that have birthdays with DataReader in a while loop. You just need to move the email sending code inside the loop.

I would recommend you to extract population report (name, birthday, hiredate, email) as excel and let wishing application take care of everything
At minimal it just need two things excel file with wish details (Date, name, email) and a configuration file (application.properties) and that is it, you are good to go.
Further there various options to run the application locally (Command line, foreground, background, docker, windows scheduler, unix cron etc) Cloud.
Application is highly configurable , you can configure various details like:
Workbook loading options
Image options to send with wishes.
SMTP Configurations
Other application level configurations like, when to send wish, belated wish, logging etc.
Disclaimer : I am the owner of the application

Related

Sending emails with a PDF attachment (C#)

I have an intranet site to manage clients' communications. There are only a few controls: a textbox for the Subject, Attachment (fileUpload control), and a multiline textbox for the content of the email.
Using the fileUpload control, I select the pdf file that I want to send to clients. All the details about the clients (name, email address, etc) is coming from a sql table.
The sending works just fine, it sends the email with the attachment. However, the PDF attachment cannot be opened. The error is that the file hasn't been correctly decoded. I am not sure where the problem is. Does anyone have an idea on where the problem is?
Here is the code (for the sending procedure):
protected void BtnSendAcctClientsEmail_Click(object sender, EventArgs e)
{
if (uplAcctngAttachment.HasFile)
{
HttpPostedFile uploadedFile = uplAcctngAttachment.PostedFile;
if (IsAcctngFileHeaderValid(uploadedFile))
{
var fileName = Path.GetFileName(uplAcctngAttachment.PostedFile.FileName);
string strExtension = Path.GetExtension(fileName);
if (strExtension != ".pdf")
{
lblAcctngFileErr.Text = "Please attach pdf files only.";
return;
}
else
{
lblAcctngFileErr.Text = "";
}
try
{
DataSet ds_Emails = new DataSet();
constr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cn = new SqlConnection(constr);
cmd = new SqlCommand("getAcctClientsEmailAddresses", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da_Emails = new SqlDataAdapter(cmd);
cn.Open();
da_Emails.Fill(ds_Emails);
cn.Close();
for (int vLoop = 0; vLoop < ds_Emails.Tables[0].Rows.Count; vLoop++)
{
string name_first = ds_Emails.Tables[0].Rows[vLoop]["contact_fname"].ToString();
email = ds_Emails.Tables[0].Rows[vLoop]["email"].ToString();
client_id = ds_Emails.Tables[0].Rows[vLoop]["id"].ToString();
clientType = "acctng";
// Build the Body of the message using name_first into a string and then send mail.
//send e-mail
string fromAddress = "associates#example.com";
string ccAddress = fromAddress;
string subject = txtAcctngSubject.Text;
string sendEmail = "Dear " + name_first + "," + Environment.NewLine + Environment.NewLine + txtAcctngMessage.Text;
sendEmail += Environment.NewLine + Environment.NewLine + "Go to https://www.example.com/crm_removal.aspx?id=" + client_id +
"&type=" + clientType + " to be removed from any future communications.";
MailAddress fromAdd = new MailAddress(fromAddress, "Associates");
MailAddress toAdd = new MailAddress(email);
MailMessage eMailmsg = new MailMessage(fromAdd, toAdd);
Attachment attachment;
attachment = new Attachment(uplAcctngAttachment.PostedFile.InputStream, fileName);
eMailmsg.Subject = subject;
eMailmsg.Attachments.Add(attachment);
eMailmsg.Body = sendEmail;
SmtpClient client = new SmtpClient();
client.Send(eMailmsg);
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
sendingErr = ex.Message;
SendErr();
}
Response.Redirect("default.aspx", false);
}
}
}
private bool IsAcctngFileHeaderValid(HttpPostedFile uploadedFile)
{
Stream s = uplAcctngAttachment.PostedFile.InputStream;
StringBuilder buffer = new StringBuilder();
int value;
for (int i = 0; i < 2; i++)
{
value = s.ReadByte();
if (value == -1)
{
throw new Exception("Invalid file data.");
}
buffer.Append(value.ToString());
}
/*extension code list for files
* 7780 = exe
* 8075 = docx
* 3780 = pdf
* 7173 = gif
* 255216 = jpg
* 13780 = png
* 6677 = bmp
* 208207 =xls, doc, ppt
* 8075 = xlsx,zip,pptx,mmap,zip
* 8297 = rar
* 01 = accdb,mdb
*/
string[] input = { "208207", "8075", "3780", "255216", "13780", "6677" };
List<string> headers = new List<string>(input);
return headers.Contains(buffer.ToString());
}
When you pass the stream to the Attachment constructor it's offset by 2 bytes because you read from it earlier in IsAcctngFileHeaderValid corrupting the data.
Reset the stream position using uplAcctngAttachment.PostedFile.InputStream.Position = 0; when IsAcctngFileHeaderValid is done reading.

Forgot password email is not delivered to user

I am new to ASP.NET and C# and this is my first big project.
Unable to send forgot password mail through ASP.NET and C#. Even, neither errors nor exceptions are displayed by Visual Studio.
These are my files:
Code Behind
//Reset password event
protected void btnResetPassword_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spResetPassword", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramUsername = new SqlParameter("#UserName", txtUserName.Text);
cmd.Parameters.Add(paramUsername);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReturnCode"]))
{
SendPasswordResetEmail(rdr["EmailID"].ToString(), txtUserName.Text, rdr["UniqueId"].ToString());
lblMessage.Text = "An email with instructions to reset your password is sent to your registered email";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Username not found!";
}
}
}
}
Send Email to Recipient, an email template is been added inline code instead of a using AlternateView.
private void SendPasswordResetEmail(string ToEmail, string UserName, string UniqueId)
{
try
{
MailMessage mailMessage = new MailMessage("Email#gmail.com", ToEmail);
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("Dear " + UserName + ",<br/><br/>");
sbEmailBody.Append("Please click on the following link to reset your password");
sbEmailBody.Append("<br/>"); sbEmailBody.Append("http://localhost:64736/SmartE/Registration/ChangePassword.aspx?uid=" + UniqueId);
sbEmailBody.Append("<br/><br/>");
sbEmailBody.Append("<b>Smart Elector</b>");
mailMessage.IsBodyHtml = true;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.Subject = "Reset Your Password";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "Email#gmail.com",
Password = "Password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
catch(Exception ex)
{
lblMessage.Text= "Record Insert Exception: " + ex.Message;
}
}
Stored procedure:
There is no output parameter defined in this stored procedure, which returns the unique code to the invoker. instead, select query is used to return the same.
CREATE PROCEDURE Spresetpassword
#UserName NVARCHAR(100)
AS
BEGIN
DECLARE #UserID INT,
#EmailID NVARCHAR(100);
SELECT
#UserID = userid,
#EmailID = emailid
FROM
globalusers
WHERE
username = #UserName;
IF (#UserID IS NOT NULL)
BEGIN
-- If username exists
DECLARE #GUID UNIQUEIDENTIFIER;
SET #GUID = NEWID();
INSERT INTO tblresetpasswordrequests (id, userid, resetrequestdatetime)
VALUES (#GUID, #UserID, GETDATE())
SELECT
1 AS ReturnCode,
#GUID AS UniqueId,
#EmailID AS EmailID
END
ELSE
BEGIN
-- If username does not exist
SELECT
0 AS ReturnCode,
NULL AS UniqueId,
NULL AS EmailID
END
END
Try this solution using membership,
protected void btnResetPassword_Click(object sender, EventArgs e)
{
MembershipUser mu = Membership.GetUser(txtResetUserName.Text.Trim());
if (mu != null)
{
if (!mu.IsLockedOut)
{
string resetPassword = Membership.GeneratePassword(8, 1);
mu.ChangePassword(mu.ResetPassword(), resetPassword);
ListDictionary replaceList = new ListDictionary();
replaceList.Add("<%UserName%>", "Name of the user");
replaceList.Add("<%NewCode%>", resetPassword);
Utility fetch = new Utility();
fetch.SendMail(mu.Email, string.Empty, "User account " + txtResetUserName.Text.Trim() + " password reset to: " + resetPassword, fetch.MailBodyTemplate(replaceList, "ResetEmailTemplate"), null);
}
}
}
Put the below code in an Utility class of your project.
public void SendMail(string to, string cc, string subject, AlternateView body, string path)
{
MailMessage message = new MailMessage(AppSettings.Default.From, to);
if (!String.IsNullOrEmpty(path)) message.Attachments.Add(new Attachment(path));
if (!String.IsNullOrEmpty(cc)) message.CC.Add(cc);
if (body != null)
{
message.AlternateViews.Add(body);
message.IsBodyHtml = true;
}
message.Body = subject;
message.Subject = subject;
Thread bgThread = new Thread(new ParameterizedThreadStart(SendEmailInBackgroud));
bgThread.IsBackground = true;
bgThread.Start(message);
}
Template based Email body
public AlternateView MailBodyTemplate(ListDictionary replaceList, string fileName)
{
AlternateView plainView = null;
string templatePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/MailTemplate/" + fileName + ".txt");
if (File.Exists(templatePath))
{
string templateContent = File.ReadAllText(templatePath);
foreach (DictionaryEntry item in replaceList)
{
if (item.Value != null)
templateContent = templateContent.Replace(item.Key.ToString(), item.Value.ToString());
else
templateContent = templateContent.Replace(item.Key.ToString(), string.Empty);
}
plainView = AlternateView.CreateAlternateViewFromString(templateContent, null, MediaTypeNames.Text.Html);
}
return plainView;
}
Your Email Template File As Follows,
File Name: ResetEmailTemplate.txt
<!DOCTYPE html>
<html><head>
<style>
.ContentBody {
color: #1331a0;
}
</style></head>
<body class="ContentBody">
<p>Dear <%UserName%>,</p>
<p>New Password for your accout is: <%NewCode%> </p>
</body>
</html>

c# Base64 in email attachment

I know that i'm stuck in a silly problem...and now i am here with hope, that you can help me. Simple situation: I need to send email with attachment from database. I have done it by myself, but...i don't know why, but attachment in email what was send is incorrect. Preciously attachment contents code, what i get from my database.
My code:
static void IncomeMessage()
{
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx");
SqlCommand cmd = new SqlCommand("Here is my SQL SELECT", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
try
{
var AID = dr["ID"].ToString();
var Ids = dr["MessageID"].ToString();
var SuperOrganizationTitle = dr["SuperOrganizationTitle"].ToString();
var Date = dr["Date"].ToString();
var Title = dr["Title"].ToString();
var Description = dr["Description"].ToString();
var DBFile = dr["File"].ToString();
var Filename = dr["FileName"].ToString();
MailMessage oMail = new MailMessage("test#test.com", "guntisvindels#gmail.com", "New message with theme: " + Title, "Message Income: " + Date + " From " + SuperOrganizationTitle + ". Message Content: " + Description);
DBFile = GetBase64(DBFile);
var bytes = Encoding.ASCII.GetBytes(DBFile);
MemoryStream strm = new MemoryStream(bytes);
Attachment data = new Attachment(strm, Filename);
ContentDisposition disposition = data.ContentDisposition;
data.ContentId = Filename;
data.ContentDisposition.Inline = true;
oMail.Attachments.Add(data);
SmtpClient oSmtp = new SmtpClient();
SmtpClient oServer = new SmtpClient("test.test.com");
oServer.Send(oMail);
}
catch (Exception ex)
{
//TraceAdd("Error=" + ex.Message.ToString());
}
}
}
For removing unnessessary data ( tags) from database File field i use this code
public static string GetBase64(string str)
{
var index1 = str.IndexOf("<content>");
index1 = index1 + "<content>".Length;
var index2 = str.IndexOf("</content>");
var kek = Slice(str, index1, index2);
return kek;
}
public static string Slice(string source, int start, int end)
{
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
return source.Substring(start, len);
}
When launching my code I can send email to me, and I'll recieve it. But message content attachment with my Base64 code from database File field. Here is a question - Where I got wrong, and how can I recieve email with correct attachment that has been written into database. Thank you for your attention
P.S Attachment in database is written correctly, because K2 integration platform can correctly display it
Here is example what database contain in File column (DBFile)
<file><name>zinojums.html</name><content>PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iQ29udGVudC1UeXBlIiBjb250ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgiIC8+PHN0eWxlPmh0bWwsYm9keXtmb250LWZhbWlseTpBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZjtmb250LXNpemU6MTBwdDt9aDF7Zm9udC1zaXplOjE0cHQ7fWgye2ZvbnQtc2l6ZToxMnB0O31we2JhY2tncm91bmQtY29sb3I6I0Y3RUVEQTttYXJnaW46MDtwYWRkaW5nOjhweDt9aHJ7aGVpZ2h0OjFweDsgYm9yZGVyOjAgbm9uZTsgY29sb3I6ICM1RjlCRDQ7IGJhY2tncm91bmQtY29sb3I6ICM1RjlCRDQ7fTwvc3R5bGU+PC9oZWFkPjxib2R5PjxoMT5JbmZvcm3EgWNpamEgbm8gVmFsc3RzIGllxYbEk211bXUgZGllbmVzdGE8L2gxPjxoMj5Eb2t1bWVudHMgcGllxYZlbXRzPC9oMj48cD5Ob2Rva8S8dSBtYWtzxIF0xIFqYSBOci4gPGI+TEFUVklKQVMgVkFMU1RTIFJBRElPIFVOIFRFTEVWxKpaSUpBUyBDRU5UUlMgQVMgKDQwMDAzMDExMjAzKTwvYj4gaWVzbmllZ3RhaXMgZG9rdW1lbnRzICI8Yj5aacWGYXMgcGFyIGRhcmJhIMWGxJNtxJNqaWVtPC9iPiIgTnIuIDxiPjU1NDYyNTY5PC9iPiBwaWXFhmVtdHMgdW4gaWVrxLxhdXRzIFZJRCBkYXR1YsSBesSTLjxiciAvPjwvcD48IS0tY29udGVudC0tPjxociAvPsWgaXMgZS1wYXN0cyBpciBpenZlaWRvdHMgYXV0b23EgXRpc2tpLCBsxatkemFtIHV6IHRvIG5lYXRiaWxkxJN0LjxiciAvPlBpZXNsxJNndGllcyBWSUQgRWxla3Ryb25pc2vEgXMgZGVrbGFyxJPFoWFuYXMgc2lzdMSTbWFpOiA8YSBocmVmPSJodHRwczovL2Vkcy52aWQuZ292Lmx2Ij5lZHMudmlkLmdvdi5sdjwvYT4uPC9ib2R5PjwvaHRtbD4=</content></file>
Right now the method you're using to create binary data from your string takes no account of the fact the string is base64-encoded specifically.
You need to replace
var bytes = Encoding.ASCII.GetBytes(DBFile);
with
var bytes = Convert.FromBase64String(DBFile);

attached .doc is opening properly in pc but in mobile its not opening properly while sending by smtp in .net

im creating .doc file and sending mail. in pc dowloaded file from
attachment is opening properly but in mobile its not opening
properly. only html tags are displaying in smart phones.can u
tell me how to render this .doc file so that in mobile also attached
file can be displayed ?
attached file is not supporting in smartphones .only html tags are
displaying.
can anyone tell in my code how to use docX library in my code?
protected void btnMail_Click(object sender, EventArgs e)
{
DisplayProgressBar();
Response.Clear();
try
{
if (Session["Projectname"] != null && Session["Projectname"].ToString() != string.Empty)
{
string Projname = Session["Projectname"].ToString();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
design.RenderControl(htmlWrite);
string strBuilder = stringWrite.ToString();
string strPath = Request.PhysicalApplicationPath + "\\Temp\\WeeklyReport of " + Projname + ".doc";
LblNoteMsg.Text = strPath;
//code changed to send mails
if (File.Exists(strPath))
{
var counter = 1;
strPath = strPath.Replace(".doc", " (" + counter + ").doc");
while (File.Exists(strPath))
{
strPath = strPath.Replace("(" + counter + ").doc", "(" + (counter + 1) + ").doc");
counter++;
}
}
using (var fStream = File.Create(strPath))
{
fStream.Close();
fStream.Dispose();
}
using(StreamWriter sWriter = new StreamWriter(strPath))
{
sWriter.Write(strBuilder);
sWriter.Close();
sWriter.Dispose();
Response.Clear();
}
DateTime input = DateTime.Now;
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime dats = DateTime.Now.AddDays(delta);
//this week
DateTime monday = input.AddDays(delta);
string MonDate = monday.ToShortDateString();
DateTime sat = monday.AddDays(5);
string SatDate = sat.ToShortDateString();
StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
string body = r.ReadToEnd();
MailMessage Msg = new MailMessage();
string MailId = txtMailId.Text;
foreach (string ss in MailId.Split(",".ToCharArray()))
{
if (string.IsNullOrEmpty(ss) == false)
{
Msg.To.Add(new MailAddress(ss));
}
}
Msg.Bcc.Add(new MailAddress("support#sunlightit.com"));
body = body.Replace("<%MonDate%>", MonDate);
body = body.Replace("<%SatDate%>", SatDate);
Msg.Subject = "Weekly status Report of " + Projname + "," + DateTime.Now.ToShortDateString() + "";
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.Attachments.Add(new Attachment(strPath));
SmtpClient MailServer = new SmtpClient();
try
{
MailServer.Send(Msg);
string reply = (Msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess).ToString();
if (reply == "OnSuccess")
{
txtMailId.Text = "";
tblMail.Visible = false;
lblMsg.ForeColor = System.Drawing.Color.Green;
lblMsg.Text = "Mail has send succesfully";
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Mail delivery unsuccessfull";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "clentscript", "alert('It is being used by another process.Please Try after sometime ');", true);
}
}
You did not make a proper .doc file. A .doc file is not composed of HTML. Word on your computer does know HTML so it will open the file, but likely the program you're using on the mobile devices will just treat it as a corrupted .doc file.
Instead, you should build a proper Word document. There's plenty of libraries for generating .docx Open Office XML Document (Word 2007) files. Find one that works for you needs, and use it.
Write the file on the server path and pass the link to user make the download:
Example:
http://yourapp.com/files/download/051651203210.doc

cannot implicitly convert type 'string' to 'int' for some reason

this code to send email to multi email address saved in access database but i have problem in line (email =read_Email.GetValue(i).ToString();) cannot implicitly convert type 'string' to 'int'
any help.
try
{
ArrayList list_emails = new ArrayList();
int i = 0, email = 0;
connection.Open(); //connection to the database.
OleDbCommand cmd_Email = new OleDbCommand("Select Email from Email_Table", connection);
OleDbDataReader read_Email = cmd_Email.ExecuteReader();
while (read_Email.Read())
{
email =read_Email.GetValue(i).ToString();
list_emails.Add(email); //Add email to a arraylist
i = i + 1 - 1; //increment or ++i
}
read_Email.Close();
connection.Close(); //Close connection
foreach (string email_to in list_emails)
{
MailMessage mail = new MailMessage();
mail.To.Add(email_to);
mail.Subject = label2.Text + " station " + label1.Text;
mail.From = new MailAddress("amrghonem20#gmail.com");
mail.Body = "Test";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Send(mail);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
you have email initialized as an integer:
int i = 0, email = 0;
and you trying to assign a string value to it:
email =read_Email.GetValue(i).ToString();
you need to either make email a string or assign an integer value to it.
Don't need to create objects in the loop, Instead use something like that:
namespace ConsoleApplication3
{
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Net.Mail;
public class Program
{
public static void Main()
{
try
{
List<string> emails = new List<string>();
int i = 0, email = 0;
connection.Open(); //connection to the database.
OleDbCommand cmd_Email = new OleDbCommand("Select Email from Email_Table", connection);
OleDbDataReader read_Email = cmd_Email.ExecuteReader();
if (read_Email.HasRows)
{
while (read_Email.Read())
{
email = read_Email.GetString(0).FirstOrDefault();
emails.Add(email);
}
read_Email.Close();
connection.Close(); //Close connection
MailMessage message = new MailMessage() {
Subject = label2.Text + " station " + label1.Text,
From = new MailAddress("amrghonem20#gmail.com"),
Body = "Test";
};
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
emails.ForEach(to =>
{
message.To.Clear();
message.To.Add(to);
smtp.Send(message);
});
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}

Categories

Resources