System.Net.Mail will read the configuration in web.config, so we will configure it in Web.config as follows:
| The code is as follows |
Copy Code |
<system.net> <mailSettings> <SMTP from= "no-reply@gmail.com" > <network host= "smtpserver" port= "" Username= "userName" password= "password" defaultcredentials= "true"/> </smtp> </mailSettings> </system.net> |
When configured, add it to the Web.config file, place it in the <configuration></configuration> node, and don't forget to introduce the System.Net.Mail namespace. Next we look at several ways to send emails:
1.asp.net Send Plain text messages
| code is as follows |
copy code |
| Try { mailmessage message = new MailMessage (); &N bsp; //Recipient message. To.add (New MailAddress ("google1@gmail.com")); message. To.add (New MailAddress ("google2@gmail.com")); //Mail title message. Subject = "Mail title"; //Mail body message. BODY = "message content"; smtpclient smtpclient = new SmtpClient (); smtpclient.send (message); } Catch { } |
The Send () method may throw an exception, so we use try to execute the method.
2.asp.net Send HTML-formatted messages
Simply set the isbodyhtml to True
Message. BODY = "This is an HTML format;"
Message. isbodyhtml = true;3.asp.net Send message with attachment
Add the attachment in
Message. Attachments.Add (New Attachment ("filename")); This article describes the way to send mail using System.Net.Mail in asp.net, and if you want to learn more, find System.Net.Mail Namespaces in MSDN to learn more.
Example:
163.com of the mailbox in the early application is supported, the subsequent application is not supported.
21cn.com seems to have given up SMTP support now, and may only be paid by the user.
Qq.com's mailbox needs to be set in the user account.
I took a sina.com mailbox to test, also need in the backstage inside
Before you can send it. The detailed code is as follows:
| code is as follows |
copy code |
| MailAddress from = new MailAddress ("sosuo8@sina.com"); MailAddress to = new MailAddress ("ahuinan@21cn.com"); MailMessage message = new MailMessage (from, to); message. Subject = "Letter from Ahanan"; message. BODY = "Hello!" Test only "; SmtpClient client = new SmtpClient (); Client. Deliverymethod = Smtpdeliverymethod.network; Client. Port = 25; Client. Host = "smtp.sina.com"; Client. Credentials = new System.Net.NetworkCredential ("sosuo8@sina.com", "123"); Response.Write (send a message to) + to. User + "," + to. Host + "," + client. Host); Client. Send (message); |
Don't forget to introduce namespaces:
| The code is as follows |
Copy Code |
Using System.Net; Using System.Net.Mail; |