jmail是一个第三方邮件操作组件,通常位于web服务器端,实现收邮件及发邮件功能(客户端用Foxmail这类就很好了)。可以利用它轻松实现发邮件、抄送、密送、多发、日志记录及收邮件功能。本章要讲的,就是:发邮件、抄送、密送、多发、日志记录。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using jmail;
using System.IO;
namespace JmailDemo
{
public class MailAPI
{
/// summary>
/// 邮件发送
/// /summary>
/// param name="zt">主题/param>
/// param name="zw">正文/param>
/// param name="getMail">收件人地址/param>
/// param name="fromMail">发件人地址,多个地址间用英文逗号或分号隔开/param>
/// param name="csMail">抄送人地址,多个地址间用英文逗号或分号隔开/param>
/// param name="msMail">密送人地址,多个地址间用英文逗号或分号隔开/param>
/// param name="fjMail">附件服务器目录,多个服务器端目录之间以英文逗号或分号隔开/param>
public void Send(string zt, string zw, string getMail, string fromMail, string csMail, string msMail, string fjMail)
{
jmail.Message jmessage = new Message();
//Jmail系统配置
jmessage.Charset = "GB2312";
jmessage.Encoding = "base64";
//配置邮件信息
jmessage.Subject = zt.Trim();//邮件主题
jmessage.HTMLBody = zw;//邮件正文
//配置收件人信息
string[] sj = getMail.Split(',', ';');
if (sj.Length > 1)
{
for (int i = 0; i sj.Length; i++)
{
jmessage.AddRecipient(sj[i], "", "");//收件人邮箱地址
}
}
else
{
jmessage.AddRecipient(sj[0], "", "");
}
//配置抄送人信息
string[] cs = csMail.Split(',', ';');
if (cs.Length > 1)
{
for (int i = 0; i cs.Length; i++)
{
jmessage.AddRecipientCC(cs[i]);
}
}
else
{
jmessage.AddRecipient(cs[0], "", "");
}
//配置密送人信息
string[] ms = msMail.Split(',', ';');
if (ms.Length > 1)
{
for (int i = 0; i ms.Length; i++)
{
jmessage.AddRecipientBCC(ms[i]);
}
}
else
{
jmessage.AddRecipient(ms[0], "", "");
}
//配置发件人信息
jmessage.ReplyTo = fromMail;//指定收件人回复的,所回复到的地址
jmessage.From = fromMail;//邮件发件人的邮箱地址
jmessage.FromName = "Test!";//邮件发件人显示的姓名
jmessage.MailServerUserName = fromMail;//用户名身份验证
jmessage.MailServerPassWord = "password";//发送邮件在服务器中的密码
//配置附件
string[] fj = fjMail.Split(',', ';');
if (fj.Length > 1)
{
for (int i = 0; i fj.Length; i++)
{
jmessage.AddAttachment(fj[i],true,null);
}
}
else
{
jmessage.AddRecipient(sj[0], "", "");
}
//配置追加信息
jmessage.AppendHTML("a href='https://www.jb51.net'>此邮件发送者/a>");
//发送邮件
for (int i = 0; i sj.Length; i++)
{
jmessage.Send("smtp.qq.com", false);//发送邮件服务器
}
//配置jmail日志
jmessage.Logging = true;
using (StreamWriter sw = new StreamWriter("E:\\log.txt", true))
{
sw.Write(jmessage.Log);
sw.Close();
}
jmessage.Close();//邮件发送完毕,关闭邮件发送状态
}
}
}
2)配置jmail邮件日志 一定要写到发送邮件的后面,且jmessage.Logging = true;和sw.Write(jmessage.Log);一定要同时使用;
4) 当出报错:the message was undeliverable.all servers failed to receive the message时,原因为smtp服务器不支持,更换smtp服务器,以前用163的没问题,但现在用163的不行了。