Sending Mail and Configuring Your Server for an ASP.NET 2.0 Email System - Sending Email with Attachments
(Page 3 of 4 )
As is introduced above, it will take all nine steps to send e-mail with attachments, which is the most complicated mode of sending e-mail. We mainly list the distinct part of the source code below:
protected void NewBtn_Click(object sender,EventArgs e)
{
///omit steps 1-6
///add the mail attachment(s)
HttpFileCollection fileList = HttpContext.Current.Request.Files;
for(int i = 0; i < fileList.Count; i++)
{ ///add each attachment
HttpPostedFile file = fileList[i];
if(file.FileName.Length <= 0 || file.ContentLength <= 0)
{ break;}
Attachment attachment = new Attachment(file.FileName);
mailMsg.Attachments.Add(attachment);
nContain += file.ContentLength;
}
if(mailMsg.IsBodyHtml == true) {nContain += 100;}
try
{ ///send email(s)
IMail mail = new Mail();
mail.SendMail(mailMsg);
///save them
int nMailID = mail.SaveAsMail(mailMsg.Subject,mailMsg.Body,from,
To.Text.Trim(),CC.Text.Trim(),mailMsg.IsBodyHtml,
nContain,mailMsg.Attachments.Count > 0 ? true : false);
if(nMailID > 0)
{ ///save the attachment(s) of the sent out email(s)
for(int i = 0; i < fileList.Count; i++)
{ ///add each attachment
HttpPostedFile file = fileList[i];
if(file.FileName.Length <= 0 || file.ContentLength <= 0)
{ break;}
///save the attachment(s) into hard disk
file.SaveAs(MapPath("MailAttachments/" + Path.GetFileName(file.FileName)));
///save the attachment(s) of the sent out email(s)
mail.SaveAsMailAttachment(
Path.GetFileName(file.FileName),
"MailAttachments/" + Path.GetFileName(file.FileName),
file.ContentType,
file.ContentLength,
nMailID);
}
}
}
catch(Exception ex)
{ ///……omitted}
Response.Redirect("~/MailDesktop.aspx");
}
So far, we've discussed sending e-mails, with all the connected steps. Next, we will examine how to configure your e-mail server to ensure that e-mail will be sent out correctly and safely.
Next: Configuring Your Email Server >>
More ASP.NET Articles
More By Xianzhong Zhu