I am trying to mail with attachments using asp.net. To do this I have done the following code:
Default.aspx.cs:
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
mailMessage.Subject = "Test Subject";
mailMessage.Body = myString.ToString();
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mailMessage.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(txtem.Text.ToString()));
mailMessage.CC.Add(new MailAddress("sample@test.com"));
mailMessage.Bcc.Add(new MailAddress("sample1@test.com"));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
Default.aspx:
<tr>
<td align="left">Passport Scan Copy</td>
<td align="left">
<asp:FileUpload ID="fuAttachment" runat="server" />
</td>
</tr>
Now with this code I can send email properly but there is no attachment! Is it because I have to upload the file separately in the server. Am actually clueless on this point can anyone please help me.
Set your form enctype to multipart/form-data. Otherwise the file does not get posted to the server and your attachment will not be sent.
<form runat="server" enctype="multipart/form-data">