• 邮件添加附件


    转载自 http://blog.163.com/china__xuhua/blog/static/199723169201243010111517/

    1、功能简介

        本实例实现了邮件、附件的发送。支持:1、一对多,即支持可以同时对多个用户发送邮件;2、支持可以同时发送多个附件。

     

    2、页面效果图

    C邮箱、附件发送 - china_xuhua - 许华
     
    3、后台代码:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Net.Mail;
    using System.Net;
    using System.Net.Mime;
    namespace SmtpEmail
    {
        public partial class Form1 : Form
        {
            #region 构造函数
            public Form1()
            {
                InitializeComponent();
            }
            #endregion
            #region 收件邮箱地址
            //邮箱地址添加到GridView中
            private void btnEmailAdd_Click(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
                {
                    if (this.txtEamilFrom.ForeColor == Color.Red)
                    {
                        MessageBox.Show("输入的收件箱格式不正确!");
                    }
                    else
                    {
                        int vRownumber = this.grdEmails.Rows.Add();
                        this.grdEmails.Rows[vRownumber].Cells[0].Value = this.txtEamilFrom.Text.Trim();
                        this.txtEamilFrom.Text = string.Empty;
                    }
                }
            }
            //邮箱地址 删除
            private void btnRemove_Click(object sender, EventArgs e)
            {
                if (this.grdEmails.Rows.Count > 0)
                {
                    //只可选中一条,进行删除
                    //int vCurrentIndex = this.grdEmails.CurrentRow.Index;
                    //this.grdEmails.Rows.RemoveAt(vCurrentIndex);
                    //支持多选删除
                    foreach (DataGridViewRow vrow in grdEmails.SelectedRows)
                    {
                        int vIndex = vrow.Index;
                        this.grdEmails.Rows.RemoveAt(vIndex);
                    }
                }
            }
            //邮箱地址 清空
            private void btnClear_Click(object sender, EventArgs e)
            {
                this.grdEmails.Rows.Clear();
            }
            #endregion
            #region 验证邮箱输入是否正确,不正确是,字体显示为红色
            //验证 发件邮箱是否正确
            private void txtEmailTo_Leave(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(this.txtEmailTo.Text.Trim()))
                {
                    bool a = IsEmail(this.txtEmailTo.Text);
                    //如果不为 邮箱,字体变为红色
                    if (IsEmail(this.txtEmailTo.Text.Trim()) == false)
                    {
                        this.txtEmailTo.ForeColor = Color.Red;
                    }
                    else
                    {
                        this.txtEmailTo.ForeColor = Color.Black;
                    }
                }
            }
            private bool IsEmail(string vEmail)
            {
                return System.Text.RegularExpressions.Regex.IsMatch(vEmail, @"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");
            }
            //验证 受件箱邮箱是否正确
            private void txtEamilFrom_Leave(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(this.txtEamilFrom.Text.Trim()))
                {
                    bool a = IsEmail(this.txtEamilFrom.Text);
                    //如果不为 邮箱,字体变为红色
                    if (IsEmail(this.txtEamilFrom.Text.Trim()) == false)
                    {
                        this.txtEamilFrom.ForeColor = Color.Red;
                    }
                    else
                    {
                        this.txtEamilFrom.ForeColor = Color.Black;
                    }
                }
            }
            #endregion
            #region 参数
           
            private string [] Files;//保存 附件文件路径
            private SmtpClient vSmtpClient = null;//设置SMTP协议
            private MailAddress vMailAddressFrom = null;//设置发件人地址,需要密码
            private MailAddress vMailAddressTo = null;//设置收件人地址,不需要密码
            private FileStream vFileStream = null;//附件文件流vMailAddressFrom
            private MailMessage vMailMessage = null;
            #endregion
            
            #region 选择文件(支持多选,可以同时上传多个附件)
            
            private void btnFileSelect_Click(object sender, EventArgs e)
            {
                OpenFileDialog vOpenSelectFile = new OpenFileDialog();
                vOpenSelectFile.Multiselect = true;
                vOpenSelectFile.Filter = "全部文件|*.*|Excel文件|*.xlsx;*.xls|Csv文件|*.csv";
                vOpenSelectFile.FilterIndex = 2;
                vOpenSelectFile.RestoreDirectory = true;
                if (vOpenSelectFile.ShowDialog() == DialogResult.OK)
                {
                    this.txtFile.Text = vOpenSelectFile.FileNames[0].ToString();
                    Files = new string[vOpenSelectFile.FileNames.Length];//实例化 Files,用以保存文件附近信息
                    for (int i = 0; i < vOpenSelectFile.FileNames.Length; i++)
                    {
                        Files[i] = vOpenSelectFile.FileNames[i].ToString();
                    }
                }
            }
            
            #endregion
            #region 验证页面必填项是否已经完善
            private bool CheckPage()
            {
                if (string.IsNullOrEmpty(this.comServer.Text))
                {
                    MessageBox.Show("请输入SMTP服务器名称","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    return false;
                }
                else if (string.IsNullOrEmpty(this.numberPort.Value.ToString()))
                {
                    MessageBox.Show("请输入SMTP服务器端口", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                else if (string.IsNullOrEmpty(this.txtEmailTo.Text))
                {
                    MessageBox.Show("请输入发件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                else if (string.IsNullOrEmpty(this.txtformPwd.Text))
                {
                    MessageBox.Show("请输入发件人邮箱密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                else if (this.grdEmails.Rows.Count < 1)
                {
                    MessageBox.Show("请输入收件人邮箱地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                else if (string.IsNullOrEmpty(this.txtEmailtitle.Text))
                {
                    MessageBox.Show("请输入邮件标题", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                return true;
            }
            #endregion
            #region 邮件发送
            //设置SMTP服务器信息
            private void SetSmtpClient(string vServerHost,int vPort)
            {
                vSmtpClient = new SmtpClient();
                vSmtpClient.Host = vServerHost;//SMTP服务器的名称
                vSmtpClient.Port = vPort;//指定端口号
                vSmtpClient.Timeout = 0;//超时时间
            }
            //验证发件人信息
            private void SetAddressForm(string vMailAddress, string vMailPwd)
            {
                //创建服务器认证
                NetworkCredential vNetwork = new NetworkCredential(vMailAddress, vMailPwd);
                //实例化 发件人地址
                vMailAddressFrom = new MailAddress(vMailAddress, "");
                //指定发件人信息,包括邮箱地址和邮箱密码
                vSmtpClient.Credentials = new NetworkCredential(vMailAddressFrom.Address, vMailPwd);
            }
            //检测附件大小
            private bool Check_File(string vFilePath,out string vInfo)
            {
                vFileStream = new FileStream(vFilePath, FileMode.Open);
                string vFileName = vFileStream.Name;
                int vSize = Convert.ToInt32(vFileStream.Length / 1024 / 1024);
                vFileStream.Close();
                if (vSize > 15)
                {
                    vInfo = "文件名为:" + vFileName + "的文件大小大于15M,允许上传。";
                    return false;
                }
                vInfo = string.Empty;
                return true;
            }
            //发送
            private void btnSaveTo_Click(object sender, EventArgs e)
            {
                if (CheckPage())//必填项验证通过
                {
                    //初始化Smtp服务器信息
                    SetSmtpClient("Smtp." + this.comServer.Text.Trim(), Convert.ToInt32(this.numberPort.Value));
                    //验证发件邮箱地址和密码
                    SetAddressForm(this.txtEmailTo.Text.Trim(), this.txtformPwd.Text.Trim());
                    vMailMessage = new MailMessage();
                    //添加收件人邮箱地址
                    foreach (DataGridViewRow vRow in grdEmails.Rows)
                    {
                        vMailAddressTo = new MailAddress(vRow.Cells[0].Value.ToString().Trim());
                        vMailMessage.To.Add(vMailAddressTo);
                    }
                    //发件人邮箱
                    vMailMessage.From = vMailAddressFrom;
                    //邮件主题
                    vMailMessage.Subject = this.txtEmailtitle.Text.Trim();
                    vMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//字体使用的编码
                    //邮件正文
                    vMailMessage.Body = this.txtEmailBody.Text.Trim();
                    vMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                    //清空历史附件,以防附件重复发送
                    vMailMessage.Attachments.Clear();
                    //添加附件
                    for (int i = 0; i < Files.Length; i++)
                    {
                        vMailMessage.Attachments.Add(new Attachment(Files[i].Trim().ToString(), MediaTypeNames.Application.Octet));
                    }
                    
                    //注册邮件发送完毕后的处理事件
                    vSmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                    //开始发送邮件
                    vSmtpClient.SendAsync(vMailMessage,"000000000");
                }
            }
            //发送邮件后所处理的函数
            private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
            {
                try
                {
                    if (e.Cancelled)
                    {
                        MessageBox.Show("发送已取消!");
                    }
                    if (e.Error != null)
                    {
                        MessageBox.Show("邮件发送失败!" + " " + "技术信息: " +"请验证,发件邮箱和密码是否正确!"+ e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show("邮件成功发出!", "恭喜!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("邮件发送失败!" + " " + "技术信息: " + Ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }  
            }
            #endregion
        }
    }
    //释放被占用的资源

       foreach (Attachment item in MailMessage_Mai.Attachments)
                            {
                                item.Dispose();
                            }

  • 相关阅读:
    Jmeter逻辑控制器
    python学习笔记——%占位符的使用
    python学习笔记——生成随机数
    python学习笔记——变量的规则
    loadrunner11中HTTP/HTML的HTML-base script的两种script type有什么区别?
    loadrunner11如何实时查看脚本的运行情况?
    loaderunner11回放脚本时如何设置【运行时行为】?
    appium学习笔记之——popupwindow控件元素无法定位
    Chrome、Firefox、IE等浏览器驱动diver程序存放目录
    npm方式安装appium环境所遇到的各种问题
  • 原文地址:https://www.cnblogs.com/TJessica/p/6575840.html
Copyright © 2020-2023  润新知