Forgot password email is not delivered to user - c#

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>

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.

Email sending in aspnet identity

I wrote following method to send emails
public ActionResult SendEmail(UserData user)
{
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created with the Comp. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.UserEmail }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return View(user);
}
catch (Exception ex)
{
throw ex;
}
}
then I'm accessing above method in main controller like following
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
// await EmailController.Sendemail(sampleData);
var emailCntrl = new EmailController();
var sendEmail = emailCntrl.SendEmail(sampleData);
this is compiling without any compile times errors. but when I debug this I can see
in this line m.Body = str... I can see a error like this
because of that I'm getting an exception
Message = "Object reference not set to an instance of an object."
How can I solve this
You don't have Request, because you create just EmailController class. When controller factory creates controller for request it passes request data to Controller.Initialize Method.
Of course the best practice is to create EmailService as was mentioned above, but as answer for your question, you can make workaround. You can pass RequestContext of parent controller to EmailController in constructor and call Initialize. It's going to look like.
public EmailController()
{
}
public EmailController(RequestContext requestContext)
{
base.Initialize(requestContext);
}
And in your controller
var emailCntrl = new EmailController(this.ControllerContext.RequestContext);
var sendEmail = emailCntrl.SendEmail(sampleData);
You can also just set the ControllerContext
var emailCntrl = new EmailController(){ControllerContext = this.ControllerContext};
var sendEmail = emailCntrl.SendEmail(sampleData);
Well given that there was no request added to controller before calling action, it would be null.
There is no need for a controller there just to send the email.
Create a class/service to handle the email and pass in any dependencies
public class EmailService {
public UserData SendEmail(UserData user, string confirmationEmailUrl) {
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, confirmationEmailUrl + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return user;
}
catch (Exception ex)
{
throw ex;
}
}
}
And get the action from main controller
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
var confirmationEmailUrl = Url.Link("Default", new { Action = "ConfirmEmail", Controller = "Account", Token = sampleData.Id, Email = sampleData.UserEmail });
var emailService = new EmailService();
var user = emailService.SendEmail(sampleData, confirmationEmailUrl);

Getting Error 'File is being used' when trying to delete file c#

I have windows service which periodically fetches data from table and creates excel file and mails it to users.After mail sending I need to delete that file. Have used following code:
public void LABInstrumentExcelGeneration(string filePath) {
try {
string connectionString = GetConnectionString(filePath);
List < LABInstruments > listLABInstrument = null;
listLABInstrument = new List < LABInstruments > ();
listLABInstrument = LABInstrumentBL.GetLABInstrumentList();
if (listLABInstrument.Count > 0) {
using(OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [table2] (SrNo string,CalibrationDoneOn Date);";
cmd.ExecuteNonQuery();
foreach(LABInstruments tc1 in listLABInstrument) {
cmd.CommandText = "INSERT INTO [table2](SrNo,CalibrationDoneOn) VALUES('" + tc1.SrNo + "','" + tc1.CalibrationDoneOn + "');";
cmd.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
}
}
} catch (Exception ex) {}
}
SendMail(filePath, role);
if (File.Exists(filePath)) {
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
But it gives error File is being used by another process.
Ho can I delete file? Moreover, i've used OLEDB for file creation. Is there any other best practise for file creation? Have tried ExcelLibrary, but files created in it does not work in all versions of office so have dropped it.
Try this:
protected virtual bool IsLocked(FileInfo fileName)
{
FileStream fStream = null;
try
{
fStream = fileName.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (fStream != null)
{
fStream.Close();
}
}
return false;
}
And then:
if (File.Exists(filePath))
{
FileInfo myfile = new FileInfo(filePath);
if(IsLocked(myfile))
{
File.Create(filePath).Close();
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
else
{
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
}
I think the problem may be that sendmail returns before it has finished using the file.
Instead of sendmail() I used this function which frees up the file for deletion:
public static void send(string subject, string body, string from, string to, List<string> attachments = null)
{
using (MailMessage message = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
message.Subject = subject;
message.Body = body;
if (attachments != null && attachments.Count > 0)
{
foreach (string s in attachments)
{
if (s != null)
{
/* this code fixes the error where the attached file is
* prepended with the path of the file */
Attachment attachment = new Attachment(s, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(s);
disposition.ModificationDate = File.GetLastWriteTime(s);
disposition.ReadDate = File.GetLastAccessTime(s);
disposition.FileName = Path.GetFileName(s);
disposition.Size = new FileInfo(s).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
}
}
using (SmtpClient client = new SmtpClient())
{
client.Send(message);
}
}
}

Sending mails automatically by console application

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

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