C#笔记8——多功能电子邮件发送程序实例

C#笔记8——多功能电子邮件发送程序实例

        最近需要使用C#发邮件的功能,利用QQ邮件服务器发送邮件,包含发送邮件功能,MD5加密解密功能,自动加载、保存用户信息功能,非常适用于项目中的一些小功能!

        效果图如下:

发送邮件

C#笔记8——多功能电子邮件发送程序实例_第1张图片

邮箱接收情况

C#笔记8——多功能电子邮件发送程序实例_第2张图片


源代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//for send mail
using System.Net.Mail;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
//for RD、WR
using System.IO;
//for Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//for MD5
using System.Security.Cryptography;

namespace MyEmail
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (tb_sender_addr.Text == "")
            {
                MessageBox.Show("发件人邮箱地址不能为空!\n");
                return;
            }
            else 
            {
                if (!MatchEmailAddr(tb_sender_addr.Text))
                {
                    MessageBox.Show("发件人邮箱格式不正确,请重新输入!");
                    tb_sender_addr.Clear();
                    return;
                }
            }

            if (tb_sender_pwd.Text == "")
            {
                MessageBox.Show("发件人邮箱密码不能为空!\n");
                return;
            }

            if (tb_receiver_addr.Text == "")
            {
                MessageBox.Show("收件人邮箱地址不能为空!\n");
                return;
            }
            else
            {
                if (!MatchEmailAddr(tb_receiver_addr.Text))
                {
                    MessageBox.Show("收件人邮箱格式不正确,请重新输入!");
                    tb_receiver_addr.Clear();
                    return;
                }
            }

            if (tb_theme.Text == "")
            {
                MessageBox.Show("邮件主题不能为空!");
                return;
            }

            if (rtb_content.Text == "")
            {
                DialogResult dr1 = MessageBox.Show("请选择是否发送!\n", "邮件内容为空!", MessageBoxButtons.YesNo);
                if (dr1 == DialogResult.Yes)
                {
                    send_email(tb_sender_addr.Text, tb_receiver_addr.Text, tb_sender_pwd.Text, tb_theme.Text, rtb_content.Text);
                }
                else if (dr1 == DialogResult.No)
                {
                    lab_log.Text = GetCurrentTime() + "  内容为空,取消发送!";
                    return;
                }
                else
                {
                    return;
                }
            }
            else
            {
                send_email(tb_sender_addr.Text, tb_receiver_addr.Text, tb_sender_pwd.Text, tb_theme.Text, rtb_content.Text);
            }
        }
        private void btn_exit_Click(object sender, EventArgs e)
        {
            SaveUserMessage(tb_sender_addr.Text,tb_receiver_addr.Text,tb_sender_pwd.Text,tb_theme.Text,rtb_content.Text);
            //关闭与该程序相关所有线程
            System.Environment.Exit(System.Environment.ExitCode);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadUserMessage();
        }

        #region send mail
        //参数说明:发件人地址,收件人地址,发件人邮箱密码,邮件主题,邮件内容
        private void send_email(string email_sender_addr, string email_receiver_addr, string email_sender_pwd, string email_subject, string email_content)
        {
            //使用QQ邮件服务器发送邮件
            try
            {
                SmtpClient smtp = new SmtpClient();
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
                smtp.Host = "smtp.qq.com";//指定SMTP服务器
                smtp.Credentials = new NetworkCredential(email_sender_addr, email_sender_pwd);//发件人邮箱地址和密码

                #region 邮件内容
                MailMessage MyMail = new MailMessage(email_sender_addr, email_receiver_addr);//发件人和收件人

                /*  
                MailMessage MyMail = new MailMessage();
                MyMail.From = new MailAddress("[email protected]");
                MyMail.To.Add(new MailAddress(email_addr));
                以上等价于MailMessage MyMail = new MailMessage(email_sender_addr,email_receiver_addr);
                */

                MyMail.Subject = email_subject;
                MyMail.SubjectEncoding = Encoding.UTF8;

                MyMail.Body = email_content;
                MyMail.BodyEncoding = Encoding.UTF8;
                MyMail.IsBodyHtml = true;
                MyMail.Priority = MailPriority.Low;
                #endregion

                smtp.Send(MyMail);
                lab_log.Text = GetCurrentTime() + "  发送邮件成功!";
            }
            catch (Exception e)
            {
                MessageBox.Show("发送邮件出错:\n" + e.ToString());
                lab_log.Text = GetCurrentTime() + "  发送邮件出错!";
                return;
            }
        }
        #endregion
        //获取当前时间
        private string GetCurrentTime()
        {
            string ct = null;

            DateTime dt = new System.DateTime();
            dt = System.DateTime.Now;
            ct = dt.ToString();
            return ct;
        }
        //匹配邮箱地址
        private bool MatchEmailAddr(string EmailAddr)
        {
            bool EmailStatus = false;
            //正则表达式字符串
            string emailStr = @"([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,5})+";
            //邮箱正则表达式对象
            Regex emailReg = new Regex(emailStr);
            if (emailReg.IsMatch(EmailAddr.Trim()))
            {
                EmailStatus = true; ;
            }
            else
            {
                lab_log.Text = "输入的不是有效的邮件地址格式";
                EmailStatus = false;
            }
            return EmailStatus;
        }
        //保存用户信息
        private void SaveUserMessage(string email_sender_addr, string email_receiver_addr, string email_sender_pwd, string email_subject, string email_content)
        {
            try {
                if (!File.Exists("./UserMsg.txt"))
                {
                    FileStream fs = File.Create("./UserMsg.txt");
                    fs.Close();
                    StreamWriter sw = new StreamWriter("./UserMsg.txt", false, System.Text.Encoding.GetEncoding("utf-8"));
                    string content = GetUserMsg_json(tb_sender_addr.Text, tb_sender_pwd.Text, tb_receiver_addr.Text, tb_theme.Text, rtb_content.Text);
                    sw.WriteLine(content);
                    sw.Close();
                    sw.Dispose();
                }
                else
                {
                    StreamWriter sw = new StreamWriter("./UserMsg.txt", false, System.Text.Encoding.GetEncoding("utf-8"));
                    string content = GetUserMsg_json(tb_sender_addr.Text, tb_receiver_addr.Text, tb_sender_pwd.Text, tb_theme.Text, rtb_content.Text);
                    sw.WriteLine(content);
                    sw.Close();
                    sw.Dispose();
                }
            }
            catch {
                lab_log.Text = GetCurrentTime() + "  保存用户信息出错!";
            }
        }
        //加载用户信息
        private void LoadUserMessage()
        {
            if (File.Exists("./UserMsg.txt"))
            {
                StreamReader sw = new StreamReader("./UserMsg.txt", System.Text.Encoding.GetEncoding("utf-8"), false);
                string str = null;
                str = sw.ReadToEnd();
                //MessageBox.Show("read:\n" + str);
                sw.Close();
                sw.Dispose();
                try
                {
                    JObject job = new JObject();
                    job = JObject.Parse(str);
                    this.tb_sender_addr.Text = job["sender_addr"].ToString();
                    this.tb_receiver_addr.Text = job["receiver_addr"].ToString();
                    this.tb_sender_pwd.Text = MD5Decrypt(job["sender_pwd"].ToString());
                    this.tb_theme.Text = job["subject"].ToString();
                    this.rtb_content.Text = job["content"].ToString();
                }
                catch
                {
                    lab_log.Text = GetCurrentTime() + "  加载用户信息失败!";
                }
            }
        }
        //将用户信息转为Json数据
        private string GetUserMsg_json(string email_sender_addr, string email_receiver_addr, string email_sender_pwd, string email_subject, string email_content)
        {
            string retmsg = null;
            try {
            JObject job = new JObject();
            job.Add(new JProperty("sender_addr",email_sender_addr));
            job.Add(new JProperty("receiver_addr", email_receiver_addr));
            job.Add(new JProperty("sender_pwd", MD5Encrypt(email_sender_pwd)));
            job.Add(new JProperty("subject", email_subject));
            job.Add(new JProperty("content", email_content));
            retmsg = job.ToString();
            }
            catch
            {
                lab_log.Text = GetCurrentTime() + "  Json 数据出错!";
            }
            return retmsg;
        }
        //MD5加密
        private string MD5Encrypt(string data)
        {
            string retmsg = null;
            string KEY_64 = "VavicApp";
            string IV_64 =  "VavicApp";
            try
            {
                byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
                byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                int i = cryptoProvider.KeySize;
                MemoryStream ms = new MemoryStream();
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
                StreamWriter sw = new StreamWriter(cst);
                sw.Write(data);
                sw.Flush();
                cst.FlushFinalBlock();
                sw.Flush();
                retmsg = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
                sw.Close();
            }
            catch (Exception x)
            {
                MessageBox.Show("MD5 加密出错:\n"+x.Message);
                lab_log.Text = GetCurrentTime() + "  MD5 加密出错!";
            }
            return retmsg;
        } 
        //MD5解密
        private string MD5Decrypt(string data)
        {
            string retmsg = null;
            string KEY_64 =  "VavicApp";
            string IV_64 = "VavicApp"; 
            try
            {
                byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
                byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
                byte[] byEnc;
                byEnc = Convert.FromBase64String(data); //把需要解密的字符串转为8位无符号数组
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream(byEnc);
                CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cst);
                retmsg = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception x)
            {
                MessageBox.Show("MD5 解密出错误:\n"+x.Message);
                lab_log.Text = GetCurrentTime() + "  MD5 解密出错误!";
            }
            return retmsg;
        } 
        //关闭窗口事件
        private void FormCloseingAll(object sender, FormClosingEventArgs e)
        {
            SaveUserMessage(tb_sender_addr.Text, tb_receiver_addr.Text, tb_sender_pwd.Text, tb_theme.Text, rtb_content.Text);
            //关闭所有线程
            System.Environment.Exit(System.Environment.ExitCode);
        }  
   
    }
}


本实例源代码:

http://download.csdn.net/download/u011127242/9714085


      若使用非qq邮箱向其它邮箱发邮件会导致发送失败,使用qq邮箱向其它任何邮箱(用gmail测试ok)都可以发送邮件的,所以使用的时候需要注意一下!一般的邮箱服务都只为自己的用户提供服务,所以非QQ邮箱是无法登陆到QQ邮箱客户端查看邮件信息的,更别说借用其服务发邮件了!
      如果想实现任意邮箱发送的功能,可以指定多个SMTP服务器(smtp.Host = "smtp.qq.com";//指定SMTP服务器)和对应的发送方式,发送之前根据邮箱地址判断邮箱类型,然后使用对应的SMTP服务就可以了,当然前提是你需要知道那么多的SMTP服务器地址,而且它们都对外开放了相应的接口才行!如果有兴趣的话可以试着做一下!




你可能感兴趣的:(C#)