Hi i am looking to clear text boxs when a user clicks a button. However the code that i have is not working. Here is my code.
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
m.Body = name.Text + Environment.NewLine + phone.Text + Environment.NewLine + email.Text + Environment.NewLine + message.Text;
m.IsBodyHtml = false;
m.To.Add("support#");
m.From = new System.Net.Mail.MailAddress(email.Text);
m.Subject = "Contact us form submisson";
m.Headers.Add("Reply-To", "your email account");
System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient();
s.UseDefaultCredentials = false;
s.Credentials = c;
s.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
s.EnableSsl = true;
s.Port = 587;
s.Host = "smtp.gmail.com";
s.Send(m);
lblCorrectCode.Text = "Contact Form Has been submited we will be in touch shortly";
name.Text = string.Empty;
phone.Text = string.Empty;
email.Text = string.Empty;
message.Text = string.Empty;
I surly hope you are not populate it in page load and not checking isPostBack
try
{
s.Send(m);
}
finally
{
lblCorrectCode.Text = "Contact Form Has been submited we will be in touch shortly";
name.Text = string.Empty;
phone.Text = string.Empty;
email.Text = string.Empty;
message.Text = string.Empty;
}
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 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);
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.
I am doing a project for class but can't figure out this small pease that has being keeping me up nights. I am creating a page dynamically and it makes a panel for each entry in a database. Now the problem is i use one button for all the buttons on each panel. I need to be able to know what button was pressed so i can send the CarID in a session to another Page.
namespace SportBucks
{
public partial class Auction : System.Web.UI.Page
{
string GCarID = "";
protected void Page_Load(object sender, EventArgs e)
{
bool bWinnerID = false;
bool bWiningBet = false;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
if ((string)Session["LoggedIn"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
Service s = new Service();
int Total = s.CarsCount();
for (int loop = Total; loop > 0; loop--)
{
Panel Panel1 = new Panel();
Panel1.ID = "pnl" + loop.ToString();
Panel1.Style["position"] = "absolute";
Panel1.Style["left"] = "155px";
Panel1.Style["top"] = "250px";
Panel1.Style["Height"] = "200px";
Panel1.Style["Width"] = "1000px";
Panel1.BackColor = System.Drawing.Color.Black;
if (loop >= 2)
{
int Top = (250 * (loop - 1));
Panel1.Style["top"] = (250 + Top + 20).ToString() + "px";
}
form1.Controls.Add(Panel1);
string Details = s.LoadCars(loop);
if (Details != null)
{
string CarID = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(CarID + "|", "");
string Man = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Man + "|", "");
string Class = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Class + "|", "");
string Type = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Type + "|", "");
string Description = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Description + "|", "");
string Reserve = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Reserve + "|", "");
string Starting = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Starting + "|", "");
string Begun = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(Begun + "|", "");
Begun = Begun.Substring(0, Begun.IndexOf(" "));
string End = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(End + "|", "");
End = End.Substring(0, End.IndexOf(" "));
string WinnerID = "";
string WinningBet = "";
if (Details.Substring(0, 1) == "|")
{
bWinnerID = false;
Details = Details.Substring(1);
}
else
{
WinnerID = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(WinnerID + "|", "");
bWinnerID = true;
}
if (Details.Substring(0, 1) == "|")
{
Details = Details.Substring(1);
bWiningBet = false;
}
else
{
WinningBet = Details.Substring(0, Details.IndexOf("|"));
Details = Details.Replace(WinningBet + "|", "");
bWiningBet = true;
}
string PicUrl = Details.Substring(0, Details.IndexOf("|"));
int Counter = PicUrl.Split(';').Length - 1;
if (Counter >= 1)
{
Image image1 = new Image();
image1.ID = "img" + CarID;
image1.ImageAlign = ImageAlign.AbsMiddle;
image1.Visible = true;
string Pic1 = PicUrl.Substring(0, PicUrl.IndexOf(";"));
image1.ImageUrl = Pic1;
image1.Style["Left"] = "10px";
image1.Style["position"] = "absolute";
image1.Style["top"] = "10px";
image1.Height = 180;
image1.Width = 230;
Panel1.Controls.Add(image1);
}
Label label1 = new Label();
label1.ID = "lblDescription" + CarID;
label1.Text = Description;
label1.ForeColor = System.Drawing.Color.Lime;
label1.BorderStyle = BorderStyle.Groove;
label1.BorderColor = System.Drawing.Color.Violet;
label1.Style["Left"] = "500px";
label1.Style["position"] = "absolute";
label1.Style["top"] = "30px";
Panel1.Controls.Add(label1);
Label label2 = new Label();
label2.ID = "lblBegun" + CarID;
label2.Text = "Auction Start: " + Begun;
label2.ForeColor = System.Drawing.Color.Lime;
label2.Style["Left"] = "270px";
label2.Style["position"] = "absolute";
label2.Style["top"] = "30px";
Panel1.Controls.Add(label2);
Label label3 = new Label();
label3.ID = "lblEnd" + CarID;
label3.Text = "Auction End: " + End;
label3.ForeColor = System.Drawing.Color.Lime;
label3.Style["Left"] = "270px";
label3.Style["position"] = "absolute";
label3.Style["top"] = "50px";
Panel1.Controls.Add(label3);
Label label4 = new Label();
label4.ID = "lblReserve" + CarID;
label4.Text = "Reserve: " + Reserve;
label4.ForeColor = System.Drawing.Color.Lime;
label4.Style["Left"] = "270px";
label4.Style["position"] = "absolute";
label4.Style["top"] = "70px";
Panel1.Controls.Add(label4);
Label label5 = new Label();
label5.ID = "lblMan" + CarID;
label5.Text = "Manufacturer: " + Man;
label5.ForeColor = System.Drawing.Color.Lime;
label5.Style["Left"] = "270px";
label5.Style["position"] = "absolute";
label5.Style["top"] = "90px";
Panel1.Controls.Add(label5);
Label label6 = new Label();
label6.ID = "lblClass" + CarID;
label6.Text = "Class: " + Class;
label6.ForeColor = System.Drawing.Color.Lime;
label6.Style["Left"] = "270px";
label6.Style["position"] = "absolute";
label6.Style["top"] = "110px";
Panel1.Controls.Add(label6);
Label label7 = new Label();
label7.ID = "lblType" + CarID;
label7.Text = "Type: " + Type;
label7.ForeColor = System.Drawing.Color.Lime;
label7.Style["Left"] = "270px";
label7.Style["position"] = "absolute";
label7.Style["top"] = "130px";
Panel1.Controls.Add(label7);
if (bWinnerID == true)
{
Label label8 = new Label();
label8.ID = "lblWinnerID" + CarID;
label8.Text = "WinnerID: " + WinnerID;
label8.ForeColor = System.Drawing.Color.Lime;
label8.Style["Left"] = "270px";
label8.Style["position"] = "absolute";
label8.Style["top"] = "130px";
Panel1.Controls.Add(label8);
}
if (bWiningBet == true)
{
Label label9 = new Label();
label9.ID = "lblWinningBet" + CarID;
label9.Text = "WinningBet R: " + WinningBet;
label9.ForeColor = System.Drawing.Color.Lime;
label9.Style["Left"] = "270px";
label9.Style["position"] = "absolute";
label9.Style["top"] = "130px";
Panel1.Controls.Add(label9);
}
/*int View = s.TimesView(CarID);
Label label10 = new Label();
label10.ID = "lblView" + CarID;
label10.Text = "Times View: " + View;
label10.ForeColor = System.Drawing.Color.Lime;
label10.Style["Left"] = "1000px";
label10.Style["position"] = "absolute";
label10.Style["top"] = "130px";
Panel1.Controls.Add(label10);*/
Button btnView = new Button();
btnView.ID = CarID;
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Click += new EventHandler(this.btnView_Click);
GCarID = CarID;
Panel1.Controls.Add(btnView);
}
}
}
}
void btnView_Click(object sender, EventArgs e)
{
Session["CarID"] = GCarID;
Response.Redirect("View.aspx");
}
}}
Try add a custom html attribute.
//code behind:
Button btnView = new Button();
btnView.ID = CarID;
//here
btnView.Attributes.Add("GCarID", CarID);
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Click += new EventHandler(this.btnView_Click);
//click
void btnView_Click(object sender, EventArgs e)
{
Session["CarID"] = ((Button)sender).Attributes["GCarID"];
Response.Redirect("View.aspx");
}
You need to understand the ASP.NET Life Cycle. Your dynamic controls need to be created in the Page_Init() stage, not the Page_Load().
What is happening is you are creating your controls in the Page_Load and when you click on a button and a post back occurs, your dynamic controls are being destroyed. The viewstate for controls is created after the Page_Init, but before the Page_Load. Therefore, your control's that you create dynamically are not keeping their values (such as the ID).
Check out this page and this page for a basic understanding of what I am talking about.
You want to use Button's Command event with CommandArgument instead of Click event.
CommandArgument is meant for that kind of storing arguments, and retrieves it back on past back.
Button btnView = new Button();
btnView.ID = CarID;
btnView.Text = "View Car";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "110px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Command += btnView_Command; // Note: Command event is used instead of Click.
btnView.CommandArgument = CarID; // Note: CarID is stored in CommandArgument.
Panel1.Controls.Add(btnView);
void btnView_Command(object sender, CommandEventArgs e)
{
string carID = e.CommandArgument.ToString();
Session["CarID"] = carID;
Response.Redirect("View.aspx");
}
What's the issue? In your event handler btnView_Click(object sender, EventArgs e), the sender would be the button which got clicked. Just cast sender to Control or Button => (sender as Control) or (sender as Button) and retrieve the carID from the ID property.. (which you set in page load) - btnView.ID = CarID;
This is of course assuming your page viewstate is working fine :) - which can be tricky with dynamically added controls in asp.net
How I can create a email attachment in C# and asp.net. I want use a html file that describe the attachment and I want it load in a kind of a message string in my application. Than I want do replace substrings in this message with other values that I get from a database. If the attachment is create I want to send it to a address.
I use a helpclass now but I think it is not the right way :/
I don't know whether it exist in .net libary. a kind of class or something.
What is the best way to do it?
here is the method how I make it now: namespave = using SmtpMail = EASendMail.SmtpMail;
private void SendMail(string vorname, string nachname, string anrede, string firma, string benutzername, string passwort, string von, string bis, string email)
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = email;
oMail.To = email;
oMail.Subject = "Company (" + nachname + ", " + vorname + ")";
SmtpServer oServer = new SmtpServer(SMTPSERVER);
try
{
Attachment header = oMail.AddAttachment(Properties.Settings.Default.ATT_header);
Attachment footer = oMail.AddAttachment(Properties.Settings.Default.ATT_footer);
Attachment left = oMail.AddAttachment(Properties.Settings.Default.ATT_left);
Attachment right = oMail.AddAttachment(Properties.Settings.Default.ATT_right);
Attachment world = oMail.AddAttachment(Properties.Settings.Default.ATT_world);
Attachment company = oMail.AddAttachment(Properties.Settings.Default.ATT_company);
Attachment weltkarte_header = oMail.AddAttachment(Properties.Settings.Default.ATT_weltkarte);
string contentID_header = "header";
header.ContentID = contentID_header;
string contentID_footer = "footer";
footer.ContentID = contentID_footer;
string ContentID_left = "left";
left.ContentID = ContentID_left;
string ContentID_right = "right";
right.ContentID = ContentID_right;
string ContentID_world = "world";
world.ContentID = ContentID_world;
string ContentID_company = "company";
company.ContentID = ContentID_company;
string ContentID_weltkarte_header = "weltkarte_header";
weltkarte_header.ContentID = ContentID_weltkarte_header;
string htmltext = "<html><body><table width='1000px' border='0' cellpadding='0' cellspacing='0'>" +
"<tr><img src=\"cid:" + contentID_header + "\"></tr>" +
"<tr><img src=\"cid:" + ContentID_weltkarte_header + "\"></tr>" +
"<tr><table border='0' cellpadding='0' cellspacing='0'>" +
"<tr>" +
"<td><img src=\"cid:" + ContentID_left + "\"></td>" +
"<td width='880' style='background-color:#efefef;'>" +
"<p align='center'>Sie haben einen Gastzugang für [Anrede] [Vorname] [Nachname],[Firma] eingerichtet.</p>" +
"<p align='center'>Im folgenden finden Sie die Zugangsdaten,</br>" +
"die für die Anmeldung am Netzwerk benötigt werden.Weitere Informationen stehen auf der Anmeldeseite zur Verfügung.</p>" +
"<p align='center'><b>Benutzername: [Benutzername]</b><br/><b>Kennwort: [Passwort]</b></p>" +
"<p align='center'>Der Zugang wird vom [ZeitVon] bis [ZeitBis] freigeschaltet sein.</p>" +
"</td>" +
"<td><img src=\"cid:" + ContentID_right + "\"></td>" +
"</tr>" +
"</table></tr>" +
"<tr><img src=\"cid:" + ContentID_company + "\"></tr>" +
"<tr><img src=\"cid:" + contentID_footer + "\"></tr>" +
"</table></body></html>";
htmltext = htmltext.Replace("[Anrede]", anrede).Replace("[Vorname]", vorname).Replace("[Firma]", firma).Replace("[Nachname]", nachname);
htmltext = htmltext.Replace("[Benutzername]", benutzername).Replace("[Passwort]", passwort);
htmltext = htmltext.Replace("[ZeitVon]", von).Replace("[ZeitBis]", bis);
oMail.HtmlBody = htmltext;
oSmtp.SendMail(oServer, oMail);
}
catch (Exception)
{
}
}
UPDATE:
Now I have create a html file with images but I bind this images with base64 coding. it works but if I read this html in the c# application I don't can send this mail. I make a breakepoint and look in my readstring but it is all right :/
here the code:
...
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = mail;
oMail.To = mail;
oMail.Subject = "company (" + lastname + ", " + firstname + ")";
SmtpServer oServer = new SmtpServer(SMTPSERVER);
try
{
using (StreamReader reader = new StreamReader(Server.MapPath("~/App_Data/zugangsmail.html"), System.Text.Encoding.Default))
{
string message = reader.ReadToEnd();
message = message.Replace("[Anrede]", title).Replace("[Vorname]", firstname).Replace("[Firma]", company).Replace("[Nachname]", lastname);
message = message.Replace("[Benutzername]", username).Replace("[Passwort]", password);
message = message.Replace("[ZeitVon]", from).Replace("[ZeitBis]", to);
oMail.HtmlBody = message;
oSmtp.SendMail(oServer, oMail);
}
}
catch (Exception ex)
{
error.Visible = true;
lblErrorMessage.Text = ex.Message;
}
...
Add the file as an embedded resource.
Open it and read the content
Send the content.
var assembly = Assembly.GetExecutingAssembly();
using (var stream = asssembly.GetManifestResourceStream("namespace.folder.filename))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}