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);
}
Related
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.
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
}
}
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);
}
}
}
}
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.
Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:
Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
My question is where am I going wrong where in this code do I put where I want the file to be saved.
The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
File1.f + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.
It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.
In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.
After you upload your file, pass strSavedLocation, which is the file location you saved the file, to your SendMessage() method.
In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage. strAttachment is the path name to your uploaded file:
var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);
It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.
If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
System.Net.Mail.MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
/*** Added mail attachment handling ***/
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strAttachment);
mailMsg.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
}
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
/*** Moved from SendMessage function ****/
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
strSaveLocation + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, strSaveLocation, "");
}
catch
{
}
}
As for the note about using StringBuilder, I agree, and I would use it like this:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);
Edited To Add:
Also, see Brad's answer above about using ContentDisposition.