C#中自动发送邮件的实现

源代码:
using System;
using System.Windows.Forms;

using System.Net.Mail;
using System.Text.RegularExpressions;

namespace 邮件
{
public partial class Form1 : Form
{
string fileName;//获取文件名
public Form1()
{
InitializeComponent();
}

    private void button发送_Click(object sender, EventArgs e)
    {
        SmtpClient client = new SmtpClient();//生成SmtpClient实例,用它发送电子邮件
        client.Host = "smtp.163.com";//指定SMTP服务器主机
        client.Port = 25;//指定要使用的端口
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "xxxxxx");//验证用户名和密码
        MailMessage message = new MailMessage();
        MailAddress from = new MailAddress(txtSender.Text);//获取输入的发件人邮箱地址
        if (txtReceiver.Text != "")
        {
            if (Regex.IsMatch(txtReceiver.Text, "\\w+@\\w+(\\.\\w+)+"))  //用正则表达式验证邮箱
            {
                MailAddress to = new MailAddress(txtReceiver.Text);//获取输入的收件人邮箱地址
                message.To.Add(to);//设置邮件接收人,MailMessage类的To属性可以Add多个接收人
            }
            else
            {
                MessageBox.Show("收件人邮箱地址不正确");
                return;
            }
        }
        else
        {
            MessageBox.Show("收件人不能为空");
            return;
        }
        if (txtCc.Text != "")
        {
            if (Regex.IsMatch(txtCc.Text, "\\w+@\\w+(\\.\\w+)+"))
            {
                MailAddress cc = new MailAddress(txtCc.Text);//获取输入的抄送人邮箱地址
                message.CC.Add(cc);//设置邮件抄送人,MailMessage类的To属性可以Add多个抄送人
            }
            else
            {
                MessageBox.Show("抄送人邮箱地址不正确");
                return;
            }
        }

        if (txtAttachFileName.Text != "")
        {
            fileName = txtAttachFileName.Text;//获取文件名
            Attachment attach = new Attachment(fileName);//获取选择的附件
            message.Attachments.Add(attach);//将附件添加到邮件中,MailMessage类的Attachments属性可以Add多个附件          
        }
        message.Subject = txtTitle.Text;//获取输入的邮件标题
        message.Body = rtbContext.Text;//获取输入的邮件正文
        message.From = from;//设置邮件发件人          
        client.Send(message);
        MessageBox.Show("发送成功");
    }

    private void button添加附件_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "所有文件(*.*)|*.*";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            txtAttachFileName.Text = ofd.FileName;
        }
    }
}

}
界面

猜你喜欢

转载自blog.csdn.net/qq_30725967/article/details/85271920
今日推荐