標籤:伺服器 命名 system res c# rgs less .net sage
C#實現簡單的SmtpClient發送郵件
分析
需要什麼
發送郵件 -- 發送內容 -- 內送郵件
流程(各功能都適用)
建立對象 -- 給對象屬性賦值 -- 調用方法
發郵件
建立郵箱伺服器對象
寄件者
收件者
建立郵件對象
郵件主題
郵件內容
設定驗證方案
設定資格認證
發送
using System.Net; --互連網命名空間
using System.Net.Mail; --互連網下的郵件命名空間
建立新浪郵箱伺服器對象
SmtpClient smtp = new SmtpClient("SMTP 事務的主機名稱或IP地址");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
MailAddress fr = new MailAddress("寄件者郵箱地址"); --寄件者是誰
MailAddress t = new MailAddress("收件者郵箱地址"); --接收者是誰
建立郵件對象
MailMessage mail = new MailMessage( fr , t );
mail.Subject = " 郵件主題 "; --給郵件對象標題屬性賦值
mail.Body = " 郵件內容 "; --給郵件對象內容屬性賦值
建立驗證方案
NetworkCredential cred = new NetworkCredential("寄件者郵箱地址", "郵箱密碼");
設定資格認證
smtp.Credentials = cred;
發送
smtp.Send(mail);
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Net; //互連網命名空間using System.Net.Mail; //互連網下的郵件命名空間public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { Button1.Click += Button1_Click; } void Button1_Click(object sender, EventArgs e) { string to = TextBox1.Text; //接收者郵箱地址 string title = TextBox2.Text; //郵件標題 string content = TextBox3.Text; //郵件內容 //建立新浪郵箱伺服器對象 SmtpClient smtp = new SmtpClient("smtp.sina.cn"); smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; //寄件者是誰 MailAddress fr = new MailAddress("1856*****@sina.cn"); //接收者是誰 MailAddress t = new MailAddress(to); //發送的郵件對象 MailMessage mail = new MailMessage(fr, t); //給郵件對象標題屬性賦值 mail.Subject = title; // mail.Subject = "[奇點網路]郵箱驗證郵件"; //給郵件對象內容屬性賦值 mail.Body = content; // mail.Body = "歡迎註冊奇點網路平台,您的郵箱驗證碼為[drtr],請在20分鐘內填寫,系統郵件請勿回複!"; //mail.Body = "yanzheng.qidian.com?i=kjwehrlkydafghdjfghwerkwehr"; //建立認證對象 NetworkCredential cred = new NetworkCredential("185********@sina.cn", "hq1234561"); //設定資格認證 smtp.Credentials = cred; //發送 smtp.Send(mail); }}View Code
WebForm 【發送郵件】