C#使用jmail组件发送邮件

时间:2021-10-29 01:57:01

1、安装

命令行环境下,到jmail.dll所在目录,运行regsvr32 jmail.dll

2、代码

#region 发送邮件
    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="sSubject"></param>
    /// <param name="sBody"></param>
    /// <param name="sToEmail"></param>
    /// <returns></returns>
    public bool Send(string sSubject,string sBody,string sToEmail)
    {
        bool blReturn = true;

jmail.Message JMail = new jmail.Message();

string strFromEmail = "发件人";

//Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send() 会根据操作结果返回true或false       
        JMail.Silent = false;
        //Jmail创建的日志,前提loging属性设置为true
        JMail.Logging = true;
        //字符集,缺省为"US-ASCII"
        JMail.Charset = "GB2312";
        //JMail.Charset = "Utf-8";
        //设置邮件的编码方式
        JMail.Encoding = "Base64";
        //信件的contentype. 缺省是("text/plain"):字符串,如果你以HTML格式发送邮件, 改为"text/html"即可。
        JMail.ContentType = "text/html";

//设置邮件信息
        JMail.Subject = sSubject.Trim();            //【邮件标题】
        JMail.Body = sBody.Trim();                  //【邮件内容】
        //JMail.HTMLBody = sBody.Trim();
        JMail.AddRecipient(sToEmail.Trim(), "", "");//【收件人】
        JMail.From = strFromEmail.Trim();           //【发件人】

//发件人邮件用户名
        JMail.MailServerUserName = "发件人邮件用户名";
        //发件人邮件密码
        JMail.MailServerPassWord = "发件人邮件密码";

//邮件添加附件,(多附件的话,可以再加一条Jmail.AddAttachment( "c:  est.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的 Jmail.ContentType="text/html";删掉。否则会在邮件里出现乱码。
        //Jmail.AddAttachment("c:est.jpg", true, null);
               
        try
        {
            //Jmail发送的方法
            //blReturn = JMail.Send("smtp.163.com", false);
            blReturn = JMail.Send("smtp.qq.com", false);
        }
        catch (Exception ex)
        {
            JMail.Close();
            return false;
        }

JMail.Close();

return blReturn;
    }
    #endregion