ASP. NET allows you to send emails + multiple recipients + multiple attachments and recipients.

Source: Internet
Author: User
Tags email account mailmessage smtpclient

ASP. NET allows you to send emails + multiple recipients + multiple attachments and recipients.

Recently, the project needs to implement the function of sending emails + adding attachments, so I learned about the System. net. mail. mailMessage and System. net. mail. smtpClient. net, according to some code on the internet, I made a Demo to share it.

Interface Effect

The old rule is to check the effect first. The mail sending interface is as follows:

The sender enters the sender's email address and password;

You can enter multiple recipients in the recipient column. Multiple recipients must be separated by semicolons (;) in English, you can also design a contact input method as needed, such as selecting a contact from the address book );

You can select multiple attachments for themes and content. Only three input controls are provided here. You can also add or delete controls or dynamically set the number of controls as required.


Let's take a look at the code and sort out the ideas based on the Code:

This is the solution structure of this small Demo:

A files folder is created in the root directory, which serves as a temporary directory on the server when the client sends an email (if you do not understand it here, please continue reading it ).

Interface code:

Default. aspx

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Default. aspx. cs" Inherits = "SendEmail_Attachments.Default" %> <! DOCTYPE html> The interface code is relatively simple.

Server code:

Default. aspx. cs

Reference the corresponding namespace

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. UI; using System. web. UI. webControls; using System. net. mail; using System. text; using System. net; using System. IO; namespace SendEmail_Attachments {public partial class Default: System. web. UI. page {// ASP. NET to send mail + multiple recipients + multiple attachments protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {format. items. add (new ListItem ("text", "0"); format. items. add (new ListItem ("HTML", "1"); format. items [0]. selected = true ;}} /// <summary> /// click event for sending the email /// </summary> /// <param name = "obj"> </param> // <param name = "e"> </param> protected void send_Click (object obj, eventArgs e) {bool flag = SendMail (); if (flag = true) {Page. clientScript. registerStartupScript (Page. getType (), "messa Ge "," <script language = 'javascript 'defer> alert ('sent successfully! '); </Script> ");} else {Page. clientScript. registerStartupScript (Page. getType (), "message", "<script language = 'javascript 'defer> alert ('failed to send! '); </Script> ");}} /// <summary> /// execution process of mail sending /// </summary> /// <returns> </returns> public bool SendMail () {// instantiate the MailMessage class, which indicates the emails that can be sent using the SmtpClient class. // here, myEmail indicates the email instance MailMessage myEmail = new MailMessage (); myEmail. from = new MailAddress (fromMail. text. trim (); // the sender of the email, myEmail. subject = subject. text. trim (); // Email Subject myEmail. isBodyHtml = format. selectedItem. value = "0 "? False: true; // set whether the email body format is in HTML format // traverse the recipient's email address and add it to the recipient's if (toMail. text. trim (). length! = 0) {string [] receivers = toMail. text. trim (). split (';'); for (int I = 0; I <receivers. length; I ++) {if (receivers [I]. length> 0) {myEmail. to. add (receivers [I]); // Add a contact for the email }}// traverse the attachments received from the client, and add them to the attachment of the email in sequence: HttpFileCollection uploadFilCol = Request. files; for (int I = 0; I <uploadFilCol. count; I ++) {string ServerFileName = ""; HttpPostedFile file = uploadFilCol [I]; if (file. contentLength! = 0) {try {string upFileName = file. fileName; string [] strTemp = upFileName. split ('. '); string upFileExp = strTemp [strTemp. length-1]. toString (); string fileName = upFileName. substring (upFileName. lastIndexOf ("\") + 1); ServerFileName = Server. mapPath ("/files") + "\" + fileName; file. saveAs (ServerFileName); // save the file to the files directory myEmail on the server. attachments. add (new Attachment (ServerFileName); // For this email Add attachment} catch (Exception ex) {Page. clientScript. registerStartupScript (Page. getType (), "message", "<script language = 'javascript 'defer> alert (" + ex. message + "); </script>"); throw ;}} myEmail. body = body. text. trim (); // The subject content of the email myEmail. bodyEncoding = Encoding. UTF8; // The encoding method of the email subject content myEmail. priority = MailPriority. high; // set the priority of this email // instantiate the SmtpClient class, which is used to send an email to the SMTP server for passing SmtpClient smtp = new Sm TpClient (); smtp. credentials = new NetworkCredential (fromMail. text. trim (), password. text. trim (); // sets the smtp credential used to verify the sender's identity. port = 25; // set the Port SMTP for smtp transactions. host = ""; // set the Host SMTP for smtp transactions. enableSsl = true; // specifies whether SmtpClient uses Secure Socket Layer (SSL) encryption to connect to try {smtp. send (myEmail); // Send this email myEmail. dispose (); // close all processes used by the mail DeleteFiles (); // delete all attachments just uploaded in files in the temporary directory} catch (Exception e) {DeleteFiles (); // Delete All uploaded attachments in files in the temporary directory. clientScript. registerStartupScript (Page. getType (), "message", "<script language = 'javascript 'defer> alert ('failed to send. Please check whether your email account and password are correct! '); </Script> ");} return true ;} /// <summary> /// traverse and delete all uploaded attachments in the files Folder /// </summary> protected void DeleteFiles () {DirectoryInfo files = new DirectoryInfo (Server. mapPath ("/files"); foreach (System. IO. fileInfo f in files. getFiles ("*. * ") {f. delete ();}}}}

Here we mainly use two classes: System. net. mail. mailMessage and System. net. mail. smtpClient, in short, MailMessage is the mail we want to send. The SmtpClient function is to send the mail under certain conditions.

System. Net. Mail. MailMessage class

It can be found on MSDN that the attributes of MailMessage are as follows:

The recipient To attributes, CC, BCC, and Attachments can all be multiple values. Therefore, in the code above, in the SendEmail () function () you can add multiple recipients and multiple attachments to the email. The BCC and CC functions are not added here, but the principle is the same.

System. Net. Mail. SmtpClient class

Attributes of SmtpClient include:


Based on these attributes and methods, you can certainly understand how SmtpClient sends emails in the Code. Here are some notes:

The Host attribute of SmtpClient is different for servers used to send different types of emails. Therefore, the Host attribute is different. If you have multiple types of mailboxes, check whether the address of the sender server in each mailbox is different, for example:

163 mail sending server address:

The sending server address of Google Mail is

Hotmail mail sending server address:

The sending server address of Foxmail and QQ mail is

Therefore, you need to determine the sender's email type to set the sender server address ~ Region ~

When the email is successfully sent or fails, you must call the DeleteFiles () function to delete the temporary files (attachments) uploaded to the server, because this example does not need to add this folder for testing on a computer, you just need to add the local file as an attachment to the MailMessage instance, but because the code myEmail is added as an attachment for MailMessage. attachments. add (new Attachment (ServerFileName); is run on the server. Therefore, if a program is released, it cannot be performed in a remote location, therefore, you must first upload the attachment to the server (the files folder is added to the server to store temporary files), add the attachment to MailMessage, and finally clear the attachment uploaded to the client.

This is done for the time being, and then optimized when necessary.

It is not easy to be original, and the reference article is attached at last:


This example is modified on the basis of this document.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.