温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

asp.net发送E-mail

发布时间:2020-07-06 21:50:34 来源:网络 阅读:738 作者:guwei4037 栏目:编程语言

发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。

先上两个实体类,用于封装成Mail对象。

/// <summary>
/// 发送邮件请求
/// </summary>
public class MailRequest
{
    #region PrivateFields
                         
    /// <summary>
    /// 文件名
    /// </summary>
    private string _fromField;
                         
    /// <summary>
    /// 返送到
    /// </summary>
    private string _toField;
                         
    /// <summary>
    /// 抄送
    /// </summary>
    private string _copyField;
                         
    /// <summary>
    /// 附件
    /// </summary>
    private string _bccField;
                         
    /// <summary>
    /// 标题
    /// </summary>
    private string _subjectField;
                         
    /// <summary>
    /// 发送人名
    /// </summary>
    private string _bodyField;
                         
    /// <summary>
    /// 类容
    /// </summary>
    private MailRequestAttachments[] _p_w_uploadsField;
                        
    #endregion
                         
    /// <summary>
    /// 发送人,多个人以分号;间隔
    /// </summary>
    public string From
    {
        get
        {
            return this._fromField;
        }
                         
        set
        {
            this._fromField = value;
        }
    }
                         
    /// <summary>
    /// 收件人,多个人以分号;间隔
    /// </summary>
    public string To
    {
        get
        {
            return this._toField;
        }
                         
        set
        {
            this._toField = value;
        }
    }
                         
    /// <summary>
    /// 抄送人,多个人以分号;间隔
    /// </summary>
    public string CC
    {
        get
        {
            return this._copyField;
        }
                         
        set
        {
            this._copyField = value;
        }
    }
                         
    /// <summary>
    /// 秘密抄送人,多个人以分号;间隔
    /// </summary>
    public string Bcc
    {
        get
        {
            return this._bccField;
        }
                         
        set
        {
            this._bccField = value;
        }
    }
                         
    /// <summary>
    /// 主题
    /// </summary>
    public string Subject
    {
        get
        {
            return this._subjectField;
        }
                         
        set
        {
            this._subjectField = value;
        }
    }
                         
    /// <summary>
    /// 内容
    /// </summary>
    public string Body
    {
        get
        {
            return this._bodyField;
        }
                         
        set
        {
            this._bodyField = value;
        }
    }
                         
    /// <summary>
    /// 附件列表
    /// </summary>
    public MailRequestAttachments[] Attachments
    {
        get
        {
            return this._p_w_uploadsField;
        }
                         
        set
        {
            this._p_w_uploadsField = value;
        }
    }
}
/// <summary>
/// 发送邮件请求附件
/// </summary>
public class MailRequestAttachments
{
    #region PrivateFields
                       
    /// <summary>
    /// 文件名
    /// </summary>
    private string _fileNameField;
                       
    /// <summary>
    /// 文件内容
    /// </summary>
    private byte[] _fileDataField;
                      
    #endregion
                       
    /// <summary>
    /// 文件名
    /// </summary>
    public string FileName
    {
        get
        {
            return this._fileNameField;
        }
                       
        set
        {
            this._fileNameField = value;
        }
    }
                       
    /// <summary>
    /// 文件内容
    /// </summary>
    public byte[] FileData
    {
        get
        {
            return this._fileDataField;
        }
                       
        set
        {
            this._fileDataField = value;
        }
    }
}

附件的内容很简单,因为在网络传输当中,是以字节流的形式传输的,因此附件的传输需要转换成字节流数组。

/// <summary>
/// 邮件帮助类
/// </summary>
public static class MailHelper
{
    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="request">邮件内容对象</param>
    /// <returns>发送邮件所遇到的异常</returns>
    public static string SendMail(MailRequest request)
    {
        try
        {
            MailMessage mail = new MailMessage();
                  
            if (string.IsNullOrEmpty(request.From))
            {
                request.From = WebConfigurationManager.AppSettings["DefaultMailFrom"];
            }
            mail.From = new MailAddress(request.From);
                  
            PaserMailAddress(request.To, mail.To);
            PaserMailAddress(request.CC, mail.CC);
            PaserMailAddress(request.Bcc, mail.Bcc);
                  
            mail.Subject = request.Subject;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.Body = request.Body;
            mail.ReplyTo = new MailAddress(request.From);
            mail.IsBodyHtml = true;
                  
            if (request.Attachments != null && request.Attachments.Length > 0)
            {
                for (int i = 0; i < request.Attachments.Length; i++)
                {
                    Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName);
                  
                    mail.Attachments.Add(mailAttach);
                }
            }
                  
            if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVER"]))
            {
                throw new ApplicationException("邮件服务无效");
            }
                  
            //Smtp Server
            SmtpClient mailClient = new SmtpClient(WebConfigurationManager.AppSettings["SMTPSERVER"]);
                  
            if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]))
            {
                //端口号
                try
                {
                    mailClient.Port = Int32.Parse(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]);
                }
                catch
                {
                    return "SMTP服务器端口设置错误,端口必须设置为数值型";
                }
            }
                  
            if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["MAILUSER"]))
            {
                mailClient.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["MAILUSER"], WebConfigurationManager.AppSettings["MAILUSERPW"]);
                mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            }
            else
            {
                mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
                  
            mailClient.Send(mail);
            mail.Dispose();
                  
            return "邮件发送成功。";
        }
        catch (SmtpFailedRecipientsException e)
        {
            return e.Message;
        }
        catch (SmtpFailedRecipientException e)
        {
            return e.Message;
        }
        catch (SmtpException e)
        {
            return e.Message;
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
                  
    /// <summary>
    /// 解析分解邮件地址
    /// </summary>
    /// <param name="mailAddress">邮件地址</param>
    /// <param name="mailCollection">邮件对象</param>
    private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection)
    {
        if (string.IsNullOrEmpty(mailAddress))
        {
            return;
        }
                  
        char[] separator = new char[2] { ',', ';' };
        string[] addressArray = mailAddress.Split(separator);
                  
        foreach (string address in addressArray)
        {
            if (address.Trim() == string.Empty)
            {
                continue;
            }
                  
            mailCollection.Add(new MailAddress(address));
        }
    }
                  
    /// <summary>
    /// 字节数组转换为流
    /// </summary>
    /// <param name="byteArray">字节数组</param>
    /// <returns>Stream</returns>
    private static Stream ByteArrayToStream(byte[] byteArray)
    {
        MemoryStream mstream = new MemoryStream(byteArray);
                  
        return mstream;
    }
}

这是一个邮件助手类,定义成static,无需实例化,直接类名.方法名的形式调用。

只需要上述3个类就可以实现发送Email了,由于上面引用的是web.config里面的信息(asp.net等命名空间,如果是winform等需要自己修改一下),这里还需要配置一下web.config,如下所示:

<appSettings>
  <!--邮件发送配置-->
  <add key="SMTPSERVER" value="smtp.qq.com"/>
  <!--这是服务器邮箱的地址,如果是新浪,则填 smtp.sina.com-->
  <add key="MAILUSER" value="xxx"/>
  <!--注意!这是对应服务器邮箱的账号-->
  <add key="MAILUSERPW" value="yyy"/>
  <!--注意!这是对应服务器邮箱的账号密码-->
</appSettings>

最后上一个测试方法,在主函数当中或者Page_Load事件中执行即可:

private void SendEmailExample()
{
    MailRequest mail = new MailRequest();
    mail.Subject = "hello,this is a e-mail sent by asp.net mailhelper.";//主题
    mail.Body = "hello,this is a e-mail sent by asp.net mailhelper.<a href='http://blog.csdn.net/guwei4037'>欢迎访问我的博客。</a>";//内容
    mail.Bcc = "512122338@qq.com";//秘密抄送人
    mail.From = "345822155@qq.com";//发送人
    mail.CC = "guwei4037@sina.com";//抄送人
    mail.To = "guwei4037@gmail.com";//收件人
       
    //读取文件到bytes
    FileStream stream = new FileStream(Path.Combine(Server.MapPath("~"), "doc\\test.txt"), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
    stream.Close();
       
    //附件
    MailRequestAttachments p_w_uploads = new MailRequestAttachments();
    p_w_uploads.FileName = "test.txt";
    p_w_uploads.FileData = bytes;
    mail.Attachments = new MailRequestAttachments[] { 
            p_w_uploads
        };
       
    string sendMainResult = "-1";
    if (!string.IsNullOrEmpty(mail.CC.Replace(";", "")) && !string.IsNullOrEmpty(mail.To.Replace(";", "")))
    {
        sendMainResult = MailHelper.SendMail(mail);
    }
    Response.Write(sendMainResult);
}

发送邮件成功,附件也能正常打开,而且多个用户都收到了电子邮件。截图为证。


asp.net发送E-mail

源代码下载,请点击这里。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI