C# Winforms 发送邮件

 

C# Winforms 发送邮件

 

 

1. 先添加两个命名空间:

using System.Net;

using System.Net.Mail;

发送邮件的发信人邮箱必须使用smtp协议的邮箱,例如163、126、sina 等邮箱( 163 、126新注册的邮箱不可用,而sina邮箱里可以自己设置是否启用smt p 协议)

 

2. 完整代码

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Net.Mail;

 

namespace Mail

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            //发送

            SmtpClient client = new SmtpClient("smtp.sina.com");    //设置 smtp 邮件协议

            client.UseDefaultCredentials = false;  

            client.DeliveryMethod = SmtpDeliveryMethod.Network;        //通过网络发送到Smtp服务器

            client.Credentials = new NetworkCredential("[email protected]", " ***** "); //通过用户名和密码认证

            MailMessage mmsg = new MailMessage(new MailAddress("[email protected]"), new MailAddress(" ******* @189.cn")); //发件人和收件人的邮箱地址  

           

            mmsg.Subject = " 邮件主题 ";       //邮件主题

            mmsg.SubjectEncoding = Encoding.UTF8;    //主题编码

            mmsg.Body = " 邮件正文 ";          //邮件正文

            mmsg.BodyEncoding = Encoding.UTF8;       //正文编码

            mmsg.IsBodyHtml = true;     //设置为HTML格式          

            mmsg.Priority = MailPriority.High;    //优先级

            try

            {

                client.Send(mmsg);

                MessageBox.Show("邮件已发成功");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

    }

}

 

3. 注意:

新浪邮箱

client.Credentials的用户名要用全称 [email protected]

163邮箱

client.Credentials的用户名不需要全称即可

client.Credentials = new NetworkCredential("adadesktopassistan", "密码");

你可能感兴趣的:(C# Winforms 发送邮件)