C# 实现发送邮件

/*定义邮箱实体类EmailInfo:*/
public class EmailInfo
{
    private string email;
    private string userName;
    private string userPwd;

    public EmailInfo()
    {
        this.email = "";
        this.userName = "";
        this.userPwd = "";
    }
    public string Email
    {
        get { return this.email; }
        set { this.email = value; }
    }
    public string UserName
    {
        get { return this.userName; }
        set { this.userName = value; }
    }
    public string UserPwd
    {
        get { return this.userPwd; }
        set { this.userPwd = value; }
    }
}
/*发送函数   receiveList:接收邮件所有邮箱  sendContent:发送内容  sendObj:发送人的邮件信息*/
public bool SendEmail(IList<string> receiveList, string sendContent,EmailInfo sendObj)
{
    bool result = false;
    if (receiveList.Count == 0 || sendObj == null || sendContent == "")
    {
        return false;
    }
    try
    {
        MailMessage mail = new MailMessage();
        mail.Subject = "通知";//设置邮件的标题
        mail.From = new MailAddress(sendObj.Email, sendObj.UserName); //设置邮件的发件人
        mail.To.Add(new MailAddress(receiveList[0],"")); //设置邮件的收件人
        for (int i = 1; i < receiveList.Count; i++)
        {
            mail.CC.Add(new MailAddress(receiveList[i],""));//设置邮件的抄送收件人
        }
        mail.Body = sendContent;
        mail.BodyEncoding = System.Text.Encoding.UTF8;//设置邮件的格式
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.High;//设置邮件的发送级别
        
        SmtpClient client = new SmtpClient("smtp.qq.com");
        client.EnableSsl = false;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential(sendObj.Email, sendObj.UserPwd);//邮箱登陆名和授权码  注意不是用户登录密码,需要登录邮箱后获取第三方登录的授权码
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Send(mail);
        result = true;
    }
    catch (Exception ex)
    {
        string error = ex.StackTrace.ToString();
    }
    return result;
}
发布了13 篇原创文章 · 获赞 0 · 访问量 879

猜你喜欢

转载自blog.csdn.net/zyx2050/article/details/102585063