C#实现邮件发送功能

2022-01-05 更新
/// <summary>
/// 邮件发送方法
/// </summary>
/// <param name="toMial">收件人邮箱</param>
/// <param name="fromMial">发件人邮箱</param>
/// <param name="userID">发件人邮箱帐号 如QQ邮箱 为QQ号码 </param>
/// <param name="userPwd">发件人邮箱受权码</param>
/// <param name="serverAddress">邮件服务地址 如QQ邮箱服务地址为smtp.qq.com</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件内容</param>
/// <returns></returns>
public bool MailSender(string toMial, string fromMial, string userID, string userPwd, string serverAddress,  string subject, string body)
{//更多源码请访问 www.luofenming.com
    try
    {
        //创建一个邮件对像
        MailMessage mailObject = new MailMessage();
        //设置发件人
        mailObject.From = new MailAddress(fromMial);
        //设置收件人
        mailObject.To.Add(new MailAddress(toMial));

        //设置邮件主题
        mailObject.SubjectEncoding = Encoding.UTF8;
        mailObject.Subject = subject;

        //设置邮件内容
        mailObject.BodyEncoding = Encoding.UTF8;//编码
        mailObject.Body = body;

        //创建一个发送邮件的对像 
        SmtpClient smtpClient = new SmtpClient();
        //服务地址  如QQ邮箱  smtp.qq.com
        smtpClient.Host = serverAddress;
        //帐号和受权码
        smtpClient.Credentials = new NetworkCredential(userID, userPwd);
        smtpClient.Send(mailObject);
        return true;
    }
    catch (Exception ex)
    {
        throw (ex);
    }
}

评论