Need to send emails to multiple users - c#

I have developed a simple alert system which will read a table in SQL and send emails accordingly. There are Usernames, Email Addresses, Messages to be sent in that SQL table. The system will read the table every 20 minutes and will send emails to the users according to their respective email address. But at the moment the system sends emails to one user only. I want to further develop this system to send emails to multiple users when one set has finished. I do not have an idea how to do this. Is there anyone who can help me with this. Code snippet would be more helpful to understand.
Below is the SQL table template
Name | Email | Factory| AlertTime| Description
User1 | user1#mydomain.com | FAC1 | 01:50:00 | UserMessage1
User1 | user1#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User1 | user1#mydomain.com | FAC3 | 03:00:00 | UserMessage3
User2 | user2#mydomain.com | FAC1 | 01:20:00 | UserMessage1
User2 | user2#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User2 | user2#mydomain.com | FAC3 | 03:00:00 | UserMessage3
User3 | user3#mydomain.com | FAC1 | 01:20:00 | UserMessage1
User3 | user3#mydomain.com | FAC2 | 01:50:00 | UserMessage2
User3 | user3#mydomain.com | FAC3 | 03:00:00 | UserMessage3
Below is my C# cord
using System;
using System.Timers;
using System.Windows.Forms;
using System.Net.Mail;
using System.Data;
using System.Speech.Synthesis;
using System.Collections.Generic;
namespace Alerts
{
public partial class frmAlerts : Form
{
SpeechSynthesizer speechSynthesizerObj;
Common ComMsg = new Common();
DataSet DatMsg = new DataSet();
AlertException error = new AlertException();
List<string> AlertList = new List<string>();
string ToName;
string ToEmail;
string TotMsg;
public frmAlerts()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
}
private void frmAlerts_Load(object sender, EventArgs e)
{
try
{
System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
timer.Elapsed += new ElapsedEventHandler(SendAlerts);
timer.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error in application Load: " + ex.Message);
}
}
public void SendAlerts(object source, ElapsedEventArgs e)
{
try
{
DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name, RptAlertRecipient.Email, RptAlerts.Factory, RptAlerts.AlertTime, RptAlerts.Description " +
"FROM RptAlerts " +
"INNER JOIN RptAlertTypes ON RptAlerts.AlertTypeID = RptAlertTypes.ID " +
"INNER JOIN RptAlertType_RecipientMapping ON RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
"INNER JOIN RptAlertRecipient ON RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
"WHERE RptAlertRecipient.Name= 'User1' " +
"ORDER BY RptAlertRecipient.Name ASC");
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
}
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
}
catch (Exception ex)
{
error.ExceptionMessage = ex.ToString();//gets the exception message to a separate class
speechSynthesizerObj = new SpeechSynthesizer();
speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
}
}
}
}

I suppose your current code only sends a mail to the last user in the list?
You will have to include the code that generates and sends the mail in your for loop.
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have "+TotMsg+ " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
}

I found a solution for that. I did some changes to the code and now it is working the way I wanted it to happen. Below is my code. Thank you everyone for your help.
using System;
using System.Data;
using System.Timers;
using System.Net.Mail;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Collections.Generic;
namespace Alerts
{
public partial class frmAlerts : Form
{
SpeechSynthesizer speechSynthesizerObj;
Common ComMsg = new Common();
DataSet DatMsg = new DataSet();
DataSet DatNames = new DataSet();
AlertException error = new AlertException();
List<string> AlertList = new List<string>();
string ToName;
string ToEmail;
string TotMsg;
string _Name;
public frmAlerts()
{
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
}
private void frmAlerts_Load(object sender, EventArgs e)
{
try
{
System.Timers.Timer timer = new System.Timers.Timer(20 * 60 * 1000);
timer.Elapsed += new ElapsedEventHandler(SendAlerts);
timer.Start();
}
catch (Exception ex)
{
MessageBox.Show("Error in application Load: " + ex.Message);
SendtoAdmin();
}
}
public void SendAlerts(object source, ElapsedEventArgs e)
{
try
{
DatNames = ComMsg.ReturnDataSet("SELECT Name FROM RptAlertRecipient ORDER BY Name DESC");
for (int i = 0; i < DatNames.Tables[0].Rows.Count; i++)
{
_Name = DatNames.Tables[0].Rows[i].ItemArray.GetValue(0).ToString();
DatMsg = ComMsg.ReturnDataSet("SELECT RptAlertRecipient.Name, RptAlertRecipient.Email, RptAlerts.Factory, RptAlerts.AlertTime, RptAlerts.Description " +
"FROM RptAlerts " +
"INNER JOIN RptAlertTypes ON RptAlerts.AlertTypeID = RptAlertTypes.ID " +
"INNER JOIN RptAlertType_RecipientMapping ON RptAlertTypes.ID = RptAlertType_RecipientMapping.AlertTypeID " +
"INNER JOIN RptAlertRecipient ON RptAlertType_RecipientMapping.AlertRecipientID = RptAlertRecipient.ID " +
"WHERE RptAlertRecipient.Name ='" + _Name + "'" +
"ORDER BY RptAlertRecipient.Name DESC");
for (int j = 0; j < DatMsg.Tables[0].Rows.Count; j++)
{
ToEmail = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(1).ToString();
ToName = DatMsg.Tables[0].Rows[j].ItemArray.GetValue(0).ToString();
AlertList.Add(DatMsg.Tables[0].Rows[j].ItemArray.GetValue(4).ToString() + "<br/>");
TotMsg = (j + 1).ToString();
}
string to = ToEmail;
string from = "helpdesk#mydomain.com";
string subject = "Alert In Time : You Have " + TotMsg + " Alerts";
string msgBody = "Dear " + ToName + ",<br/><br/>";
msgBody += "<b>You Have " + TotMsg + " Alerts</b><br/><br/>";
msgBody += string.Join("<br/>", AlertList);
msgBody += "<br/><br/>Regards<br/>Sent by Alert Service<br/>(Please do not reply to this email.)";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "password");
clnt.Send(msg);
AlertList.Clear();
}
}
catch (Exception ex)
{
error.ExceptionMessage = ex.ToString();
speechSynthesizerObj = new SpeechSynthesizer();
speechSynthesizerObj.SpeakAsync(ex.Message);//Speaks the Error
SendtoAdmin();
}
}
#region SendMails
protected void SendtoAdmin()
{
//Send mail to Admin
string to = "admin#mydomain.com";
string from = "helpdesk#mydomain.com";
string subject = "System Failure";
string msgBody = "Dear Admin,<br/><br/>System Failure in Alert System.<br/>Please Attend Immediately.<br/>"+ error.ExceptionMessage + "<br/><br/>Regards<br/>Sent By Alert System";
MailMessage msg = new MailMessage(from, to, subject, msgBody);
msg.IsBodyHtml = true;
SmtpClient clnt = new SmtpClient("outlook.mydomain.local", 25);
clnt.EnableSsl = false;
clnt.Credentials = new System.Net.NetworkCredential("helpdesk#mydomain.com", "sl#ithd");
clnt.Send(msg);
}
#endregion
}
}

Related

Can I incorporate error handling into my API?

I have an API that loops through addresses and cleanses them. I am testing it with about 40k addresses, and it takes several hours to loop through thousands of them. Sometimes it throws an error and closes out the application and I have to start it over. Is there a way that I can write in error handling into the catch, that if there is an error, it will just log it, but continue running the app?
I am using VS 2019, C#, Windows Forms.
public class Elements
{
public string streetaddress1 { get; set; }
public string streetaddress2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
}
void Output(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
txtResponse.SelectionStart = txtResponse.TextLength;
txtResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void btnMultiple_Click(object sender, EventArgs e)
{
//Loads address that need to be cleansed
string filePath = #"C:data.csv";
List<Elements> addresses = new List<Elements>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
Elements newElement = new Elements();
newElement.streetaddress1 = entries[0];
newElement.streetaddress2 = entries[1];
newElement.city = entries[2];
newElement.state = entries[3];
newElement.zip = entries[4];
addresses.Add(newElement);
}
foreach (var Element in addresses)
{
Output($"{ Element.streetaddress1 } { Element.city} { Element.state } { Element.zip } " +
$"{ Element.country }");
var venvMulti = new AreaLookup.VertexEnvelope();
var clientMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqMulti = new AreaLookup.TaxAreaRequestType();
var reqresMulti = new AreaLookup.TaxAreaResultType();
var resMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLMulti;
string outputXMLMulti;
var TALMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateMulti = new DateTime();
var resTypeMulti = new AreaLookup.TaxAreaLookupResultType();
var postalMulti = new AreaLookup.PostalAddressType();
string StrNoteMulti = "";
int i, y;
var x = default(int);
postalMulti.MainDivision = Element.state;
postalMulti.City = Element.city;
postalMulti.PostalCode = Element.zip;
postalMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateMulti = Conversions.ToDate("2020-12-11");
TALMulti.asOfDate = TALasofDateMulti;
TALMulti.Item = postalMulti;
reqMulti.TaxAreaLookup = TALMulti;
var LITMulti = new AreaLookup.LoginType();
venvMulti.Login = new AreaLookup.LoginType();
venvMulti.Login.UserName = "****";
venvMulti.Login.Password = "****";
venvMulti.Item = reqMulti;
inputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(inputXMLMulti);
try
{
clientMulti.LookupTaxAreas90(ref venvMulti);
resMulti = (AreaLookup.TaxAreaResponseType)venvMulti.Item;
outputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(outputXMLMulti);
var loopTo = resMulti.TaxAreaResult.Length - 1;
}
catch (NullReferenceException)
{
Console.WriteLine("Null");
}
reqMulti = default;
reqresMulti = default;
resMulti = default;
void debugOutputCleansedMulti(string strDebugTextCleansedMulti)
{
try
{
System.Diagnostics.Debug.Write(strDebugTextCleansedMulti + Environment.NewLine);
txtCleansed.Text = txtCleansed.Text + strDebugTextCleansedMulti + Environment.NewLine;
txtCleansed.SelectionStart = txtCleansed.TextLength;
txtCleansed.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
debugOutputCleansedMulti("Address Cleanse Started: ");
var venvCleansedMulti = new AreaLookup.VertexEnvelope();
var clientCleansedMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqCleansedMulti = new AreaLookup.TaxAreaRequestType();
var reqresCleansedMulti = new AreaLookup.TaxAreaResultType();
var resCleansedMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLCleansedMulti;
string outputXMLCleansedMulti;
var TALCleansedMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateCleansedMulti = new DateTime();
var resTypeCleansedMulti = new AreaLookup.TaxAreaLookupResultType();
var postalCleansedMulti = new AreaLookup.PostalAddressType();
string StrNoteCleansedMulti = "";
int a, b;
var c = default(int);
postalCleansedMulti.MainDivision = Element.state;
postalCleansedMulti.City = Element.city;
postalCleansedMulti.PostalCode = Element.zip;
postalCleansedMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateCleansedMulti = Conversions.ToDate("2020-12-11");
TALCleansedMulti.asOfDate = TALasofDateCleansedMulti;
TALCleansedMulti.Item = postalCleansedMulti;
reqCleansedMulti.TaxAreaLookup = TALCleansedMulti;
var LITCleansedMulti = new AreaLookup.LoginType();
venvCleansedMulti.Login = new AreaLookup.LoginType();
venvCleansedMulti.Login.UserName = "****";
venvCleansedMulti.Login.Password = "****";
venvCleansedMulti.Item = reqCleansedMulti;
int j = 1;
//inputXMLCleansed = resCleansed.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " - " + resCleansed.TaxAreaResult[0].PostalAddress[0].PostalCode + " - " + resCleansed.TaxAreaResult[0].confidenceIndicator;
//debugOutputCleansed(inputXMLCleansed);
try
{
clientCleansedMulti.LookupTaxAreas90(ref venvCleansedMulti);
resCleansedMulti = (AreaLookup.TaxAreaResponseType)venvCleansedMulti.Item;
debugOutputCleansedMulti(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " | Street Address 1" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + " | Street Address 2" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + " | County" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + " | City" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + " | Zip Code" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + " | State" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator + " | Confidence Indicator");
string pathCleansed = #"C:\dev\data\data.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].Country + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
txtCounter.Text = j.ToString();
j++;
var loopTo = resCleansedMulti.TaxAreaResult.Length - 1;
for (b = 0; b <= loopTo; b++)
{
if (c == 0)
{
StrNoteCleansedMulti = resCleansedMulti.TaxAreaResult[b].PostalAddress[0].StreetAddress1 + " - " + resCleansedMulti.TaxAreaResult[b].confidenceIndicator; c = 1;
}
else
{
StrNoteCleansedMulti += ", " + resCleansedMulti.TaxAreaResult[b].taxAreaId + " - " + resMulti.TaxAreaResult[b].confidenceIndicator;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
reqCleansedMulti = default;
reqresCleansedMulti = default;
resCleansedMulti = default;
}
}
Essentially you need a way to save your work in progress. One pattern would be to load the file and store it in a database, then as you process each line you mark off which item you have processed. If you did this I would split the code into different modules, importing file, processing file, and exporting results.
Another simpler approach might be to write the results out as you process them, and record the line number from the input file. Then if you have to restart, find the last line you output and use that to skip reprocessing the items in your input file

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.

Why does It send a mail twice?

I have a program that sends automatic mails to people who are on my database. I am taking the people to data table with this code:
private DataTable verileri_cek()
{
consql.Open();
string kayit = "SELECT * from kisiler where
DATEPART(DAY,dogumtarihi)=DATEPART(DAY,GETDATE()) and
DATEPART(MONTH,dogumtarihi)=DATEPART(MONTH,GETDATE())";
SqlCommand komut = new SqlCommand(kayit, consql);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt =new DataTable();
da.Fill(dt);
consql.Close();
return dt;
}
Then I want to send mail to people who are on the data table. I have to recieve 2 emails for my two different e-mail. But It send two times for the one. Why?
This is my part of code to send mail:
private void Saat10()
{
DataTable dt=verileri_cek();
if (dt.Rows.Count > 0)
{
SmtpClient client = new SmtpClient();
MailMessage mesaj = new MailMessage();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["durum"].ToString() == "Akademik")
{
mesaj.IsBodyHtml = true;
mesaj.Subject = "Doğum Günü";
mesaj.Body = "Sayın Akademik Personelimiz" + dt.Rows[i]["isim"].ToString() + " " + dt.Rows[i]["soyisim"].ToString() + " " + "Doğum Gününüz Kutlu Olsun";
}
else
{
mesaj.IsBodyHtml = true;
mesaj.Subject = "Doğum Günü";
mesaj.Body = "Sayın İdari Personelimiz" + " " + dt.Rows[i]["isim"].ToString() + " " + dt.Rows[i]["soyisim"].ToString() + " " + "Doğum Gününüz Kutlu Olsun";
}
mesaj.To.Add(dt.Rows[i]["mail"].ToString());
client.Send(mesaj);
}
}
}
Can you help me please?
You have to create a new MailMessage object for each user:
private void Saat10()
{
DataTable dt=verileri_cek();
if (dt.Rows.Count > 0)
{
SmtpClient client = new SmtpClient();
MailMessage mesaj = new MailMessage();
for (int i = 0; i < dt.Rows.Count; i++)
{
mesaj = new MailMessage();
// all other code
}
}
}
If I've understood what you are saying correctly, and you want a new message for each row in the returned table, then you need to move:
MailMessage mesaj = new MailMessage();
..into your For..Loop instead of just after you've checked if there are rows.
for (int i = 0; i < dt.Rows.Count; i++)
{
MailMessage mesaj = new MailMessage();
//< rest of your code here>
mesaj.To.Add(dt.Rows[i]["mail"].ToString());
client.Send(mesaj);
}
First of all I would recommend printing each time what you've got before you actually send the mails. Of course you can also debug. In your example you need to create the message inside the for loop.
for (int i = 0; i < dt.Rows.Count; i++)
{
MailMessage mesaj = new MailMessage();
if (dt.Rows[i]["durum"].ToString() == "Akademik")
{
mesaj.IsBodyHtml = true;
mesaj.Subject = "Doğum Günü";
mesaj.Body = "Sayın Akademik Personelimiz" + dt.Rows[i]["isim"].ToString() + " " + dt.Rows[i]["soyisim"].ToString() + " " + "Doğum Gününüz Kutlu Olsun";
}
else
{
mesaj.IsBodyHtml = true;
mesaj.Subject = "Doğum Günü";
mesaj.Body = "Sayın İdari Personelimiz" + " " + dt.Rows[i]["isim"].ToString() + " " + dt.Rows[i]["soyisim"].ToString() + " " + "Doğum Gününüz Kutlu Olsun";
}
mesaj.To.Add(dt.Rows[i]["mail"].ToString());
client.Send(mesaj);
}

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);
}
}
}
}

New line in code is not working

I'm using this code to send mails to my coworkers. The part at the mailMessage.Body, when I'm using "\r\n" is not working. Instead of showing the e-mail like this:
entity.PrimaryMeal.Title
entity.ScondaryMeal.Title
Porosine mund ta beni ketu: <> (this is in my language AL)
it is showing like this:
entity.PrimaryMeal.Title, entity.ScondaryMeal.Title. Porosine mund ta beni ketu: <>
What am I doing wrong?
private void SendMail(string MailReciever)
{
Configuration configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettingsSectionGroup = (MailSettingsSectionGroup)configuration.GetSectionGroup("system.net/mailSettings");
string MailSender = mailSettingsSectionGroup.Smtp.From;
string Username = mailSettingsSectionGroup.Smtp.Network.UserName;
string UserPassword = mailSettingsSectionGroup.Smtp.Network.Password;
string SmtpServer = mailSettingsSectionGroup.Smtp.Network.Host;
int Port = mailSettingsSectionGroup.Smtp.Network.Port;
bool UseSsl = mailSettingsSectionGroup.Smtp.Network.EnableSsl;
bool UseDefaultCredentials = mailSettingsSectionGroup.Smtp.Network.DefaultCredentials;
using (SmtpClient smtpClient = new SmtpClient())
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.To.Add(MailReciever);
mailMessage.From = new MailAddress(MailSender);
mailMessage.Subject = ConfigurationManager.AppSettings["NewMailSubject"];
smtpClient.Host = SmtpServer;
smtpClient.UseDefaultCredentials = UseDefaultCredentials;
smtpClient.Port = Port;
smtpClient.Credentials = new NetworkCredential(Username, UserPassword);
smtpClient.EnableSsl = UseSsl;
#region MailMessageBody
var entity = Factory.Orders.List(item => item.OrderDate == DateTime.Today).ToList().FirstOrDefault();
if (entity.SecondaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else if (entity.TertiaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ",\r\n" + entity.SecondaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else
{
mailMessage.Body = entity.PrimaryMeal.Title + ",\r\n" + entity.SecondaryMeal.Title + ",\r\n" + entity.TertiaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
#endregion
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
}
}
mailMessage.IsBodyHtml = true;
You are sending your email as Html (which ignores raw line breaks), you should add the <br> tag instead (or work with paragraphs).
if (entity.SecondaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ".<br>Porosine mund ta beni ketu: http://10.200.30.11:8888";
}
else if (entity.TertiaryMealId == -1)
{
mailMessage.Body = entity.PrimaryMeal.Title + ",<br>" + entity.SecondaryMeal.Title + ".\r\nPorosine mund ta beni ketu: http://10.200.30.11:8888";
}
else
{
mailMessage.Body = entity.PrimaryMeal.Title + ",<br>" + entity.SecondaryMeal.Title + ",<br>" + entity.TertiaryMeal.Title + ".<br>Porosine mund ta beni ketu: http://10.200.30.11:8888";
}
I think its better to send HTML mail. That means you need to put <br/> instead of \r\n and set Message body type as HTML.

Categories

Resources