cool hit counter ASP. NET implements sending emails + multiple recipients + multiple attachments_Intefrankly

ASP. NET implements sending emails + multiple recipients + multiple attachments


Copyright Notice: This article is a blog owner Original Article, without a blog owner Permission not to reproduce。 https://blog.csdn.net/huyuyang6688/article/details/42011431

Net.Mail.MailMessage and System.Net.Mail.SmtpClient and several other classes for sending emails in .

Interface Effect

As usual, let's start with the results, here is the interface for sending the email.

The sender enters the sender's e-mail address, password.

You can enter more than one recipient in the To field, and you need to use the semicolon " ; " to separate them (this is of course only one way, and the way of entering contacts can be designed to suit the needs, e.g. selecting contacts from the address book, etc.).

Theme, content without further ado, attachments can choose multiple attachments, here only three input controls are drawn, you can also add or delete controls or dynamically set the number of controls according to demand.

code

See the code below to organize the ideas based on the code.

Here is the solution structure for this little demo.

The root directory creates a files folder that serves as a temporary directory on the server side when the client sends mail (if you don't understand here, please continue on).

Interface code.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SendEmail_Attachments.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table align="center" border="0" cellpadding="0" cellspacing="0" width="776">
                <tr>
                    <td>
                        <table align="center" border="0" cellpadding="4" cellspacing="1" width="600" bgcolor="#cccccc">
                            <tr>
                                <td colspan="2" bgcolor="#f0f0f0" align="center"> mail+ multi-recipient+ multi-annex</td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px"> sender:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <asp:TextBox ID="fromMail" runat="server" Width="300" /></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px"> close   code:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <asp:TextBox ID="password" runat="server" Width="300" TextMode="Password"/></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px; height: 32px"> recipient (of mail):</td>
                                <td bgcolor="#ffffff" align="left" style="height: 32px">
                                    <asp:TextBox ID="toMail" runat="server" TextMode="multiLine" Width="300px" Height="22"/><asp:Label ID="Label1" runat="server" Text=" Please separate multiple recipients with a semicolon" ForeColor="Red"></asp:Label></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px"> owner     mention:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <asp:TextBox ID="subject" runat="server" Width="300" /></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="center" style="width: 74px"> attach    item:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <input type="file" id="upfile1" runat="server" style="width: 297px"/>
                                    <input type="file" id="upfile2" runat="server" style="width: 297px"/>
                                    <input type="file" id="upfile3" runat="server" style="width: 297px"/>
                                </td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px"> inner     contain:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <asp:TextBox ID="body" TextMode="multiLine" runat="server" Width="500px" Height="200" /></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" align="right" style="width: 73px"> (classical) obstruct     style:</td>
                                <td bgcolor="#ffffff" align="left">
                                    <asp:RadioButtonList ID="format" runat="server" /></td>
                            </tr>
                            <tr>
                                <td bgcolor="#f0f0f0" colspan="2" align="center">
                                    <asp:Button ID="send" runat="server" Text=" sending" OnClick="send_Click" />
                                    <asp:Button ID="reset" runat="server" Text=" reprovision" />
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

The interface code is relatively simple, so I won't go into it again here.

server-side code:

Default.aspx.cs

Note the reference to 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 sends emails with attachments http://blog.csdn.net/hope94/article/details/4364471
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                format.Items.Add(new ListItem(" copies", "0"));
                format.Items.Add(new ListItem("HTML", "1"));
                format.Items[0].Selected = true;
            }
        }
        /// <summary>
         /// Click event for sending emails
        /// </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(), "message", "<script language='javascript' defer>alert(' Sent successfully!');</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert(' failure to send!');</script>");
            }
        }

        /// <summary>
         /// Execution process of sending emails
        /// </summary>
        /// <returns></returns>
        public bool SendMail()
        {
             // Instantiate the MailMessage class, which represents an email that can be sent using the SmtpClient class
             // Here myEmail is the example of the email that will be sent
            MailMessage myEmail = new MailMessage();
            myEmail.From = new MailAddress(fromMail.Text.Trim());                   // electronic mail item initial recognition item human
            myEmail.Subject = subject.Text.Trim();                                  // electronic mail item of owner mention
            myEmail.IsBodyHtml = format.SelectedItem.Value == "0" ? false : true;   // Set up e-mail item main text (as opposed footnotes) (classical) obstruct style whether it isHTML (classical) obstruct style

            // travel throughout recipient (of mail) E-mail address, and add to this post item of recipient (of mail) Li (surname)       
            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]);                               // For this eMail item Add contact
                    }
                }
            }

            // Iterates over the attach item, and add them in order to the post item of attach item in
            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);   // Post this article item Temporarily saved to the server side of thefiles table of contents
                        myEmail.Attachments.Add(new Attachment(ServerFileName));  // For this eMail item increase attach item
                    }
                    catch (Exception ex)
                    {
                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert(" + ex.Message + ");</script>");
                        throw;
                    }
                }
            }

            myEmail.Body = body.Text.Trim();           // electronic mail item of owner body inner contain
            myEmail.BodyEncoding = Encoding.UTF8;      // electronic mail item owner body inner contain approved by code fair and square style
            myEmail.Priority = MailPriority.High;      // Set up this email item priority

            // instantiatedSmtpClient kind, should kind It is used to send electronic mail item sending up to SMTP  server in order to deliver
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new NetworkCredential(fromMail.Text.Trim(), password.Text.Trim());   // The settings are used to validate the issuance of item Vouchers for the identity of the person
             smtp. Port = 25;                            // Set the port used for SMTP transactions

            // depending on the situation item Human eMail item address determination hair item Server Address
            if (fromMail.Text.Trim().Length != 0)
            {
                string[] addressor = fromMail.Text.Trim().Split(new Char[] { '@', '.' });
                switch (addressor[1])
                {
                    case "163":
                        smtp.Host = "smtp.163.com";
                        break;
                    case "gmail":
                        smtp.Host = "smtp.gmail.com";
                        break;
                    case "hotmail":
                        smtp.Host = "smtp-mail.outlook.com";
                        break;
                    case "qq":
                        smtp.Host = "smtp.qq.com";
                        break;
                    case "foxmail":
                        smtp.Host = "smtp.qq.com";
                        break;
                    case "sina":
                        smtp.Host = "smtp.sina.com.cn";
                        break;            
                }
            }
            smtp.EnableSsl = true;                    // designate SmtpClient  Whether to use Secure Sockets Layer(SSL) plus close join
                               
            try
            {
                smtp.Send(myEmail);                   // sending postal service item
                myEmail.Dispose();                    // Close Mail item All processes used
                DeleteFiles();                        // Delete temporary directoryfiles All of the just uploaded in attach item
            }
            catch (Exception e)
            {
                DeleteFiles();                        // Delete temporary directoryfiles All of the just uploaded in attach item
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert(' failure to send, Please check your email account harmony close code Is it filled out correctly!');</script>"); ;
            }
            return true;
        }

        /// <summary>
        ///  Traversal Deletefiles gentle item sandwich inner All just uploaded attach item
        /// </summary>
        protected void DeleteFiles()
        {
            DirectoryInfo files = new DirectoryInfo(Server.MapPath("/files"));
            foreach (System.IO.FileInfo f in files.GetFiles("*.*"))
            {
                f.Delete();
            }
        }
    }
}

There are two main classes used here.System.Net.Mail.MailMessage harmonySystem.Net.Mail.SmtpClient , simply put, a MailMessage is an email that we want to send, and SmtpClient's function is to send that email out under certain conditions.

System.Net.Mail.MailMessage kind

As you can find out on MSDN, the properties of MailMessage are as follows.

Where the To attribute, Cc CC, BCC and Attachments can be multiple values, so in the above code, it is only in the send function SendEmail() that you can add multiple recipients and multiple attachments to the email, here there is no function to add BCC and Cc, but the reason is the same.

System.Net.Mail.SmtpClient kind

The properties of SmtpClient are.

The methods are.

Based on these properties and methods, you will certainly be able to understand how SmtpClient in the code sends emails out, with a few caveats noted here.

SmtpClient's Host property, the servers used to send different types of emails are different, so the Host property is also different, if you have more than one kind of mailbox, then you can see if the address of the outgoing server is different for each of your mailboxes, for example.

The outgoing mail server address of 163 mailbox is: smtp.163.com

The outgoing mail server address for Google Mail is: smtp.gmail.com

The outgoing mail server address for Hotmail mailbox is: smtp-mail.outlook.com

Foxmail harmonyQQ Mailbox sending item The server address is:smtp.qq.com

So in the code, a Switch is added to set the outgoing server address based on the sender email type ~∪~

Finally, when the email is sent successfully or fails, you need to call the DeleteFiles() function to delete the temporary files (attachments) just uploaded to the server, to say a few words about why to add this files folder, because this example on a computer to do tests do not need to add this folder at all, directly add the local files as attachments to the MailMessage instance on the line, but because the code for MailMessage to add attachments myEmail.Attachments.Add(new Attachment(ServerFileName)); It is running on the server side, so if the program is published, it is not feasible to perform the operation offsite, so you need to upload the attachment to the server side first (here just add the files folder to the server side to store temporary files), then add that attachment for MailMessage, and finally clean up the attachment uploaded to the client.

Make it like this for now, and optimize it later when there is a need for it.

The original is not easy to create and ends with a reference to the article.

http://blog.csdn.net/hope94/article/details/4364471

This example is a modification of this article


Recommended>>
1、Artificial intelligence can now model in 3D 3D printing future without having to model it yourself
2、Appendicitis Facebooks recent tweaks remind me of Racer
3、Countries could be caught off guard if satellites experience cyber attacks
4、Wang Pengjie chairman of the Henan Provincial Committee of the Communist Party of China investigated a number of big data enterprises on Wisdom Island and made three recommendations
5、Domain wall detection queries and solutions

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号