Now i fixed the filtering of file extension but i have a problem on “catch” it doesn’t display any error message but good, it is not sending the email with wrong file type.
but my problem is here:
catch(Exception err)
{
Console.WriteLine(err.Message);
lblStatus.ForeColor = Color.Red;
lblFile.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while submitting your application";
lblFile.Text = " Accepts .doc, .docx and .pdf files only!";
return ;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fileUpload1.HasFile)
{
var fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
try
{
string strExtension = Path.GetExtension(fileName);
if (strExtension == ".docx" || strExtension == ".doc" || strExtension == ".pdf")
{
MailMessage myMessage = new MailMessage();
myMessage.To.Add(new MailAddress("someone@yahoo.com"));
myMessage.From = new MailAddress("me@gmail.com");
myMessage.Subject = txtSubject.Text;
myMessage.Body = "<html><body><br/><b>Sender Name:</b> " + txtName.Text.ToString() + "<br/><br/><b>Email:</b> " + txtEmail.Text.ToString() +
"<br/><br/><b>Contact Number:</b> " + txtContact.Text.ToString() + "<br/><br/><b>Subject</b> " + txtSubject.Text.ToString() +
"<br/><br/><b>CV Summary:</b><br/><br/>" + txtSummary.Text.ToString() + "</body></html>";
myMessage.IsBodyHtml = true;
myMessage.Attachments.Add(new Attachment(fileUpload1.PostedFile.InputStream, fileName));
SmtpClient mySmtp = new SmtpClient();
mySmtp.Host = "smtp.gmail.com";
mySmtp.Credentials = new System.Net.NetworkCredential("me@gmail.com", "mypassword");
mySmtp.EnableSsl = true;
mySmtp.Send(myMessage);
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "We will contact you once you have been shortlisted to the position you are applying for. <br/> You may now close this window.";
txtName.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
txtSummary.Text = "";
txtContact.Text = "";
}
}
catch(Exception err)
{
Console.WriteLine(err.Message);
lblStatus.ForeColor = Color.Red;
lblFile.ForeColor = Color.Red;
lblStatus.Text = "There was an error occured while submitting your application";
lblFile.Text = " Accepts .doc, .docx and .pdf files only!";
return ;
}
}
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
txtSummary.Text = "";
txtContact.Text = "";
}
Here is a nicer way to do it:
Basically, you only want to catch exceptions i.e. IO or mail sending failures.
This code will return if the extension is not a doc, docx or pdf and not call the send mail code.
Also, the myMessage.From() address must be a valid email address and the one that you supplied via your NetworkCredentials()
Here is a cut down version of the code that I have tested and verified that it is working: