public classApacheMailTest {//smtp服务器
private String hostName = "smtp.qq.com";//帐号与密码
private String userName = "779554589";private String password = "这是个秘密";//发件人
private String fromAddress = "779554589@qq.com";//发件人姓名
private String fromName = "loadfate";public static voidmain(String[] args) throws Exception {//收件人与收件人名字
String toAddress = "loadfate@163.com";
String toName= "loadfate";
ApacheMailTest test= newApacheMailTest();//所有的异常都为处理,方便浏览
test.sendSimpleEmail(toAddress, toName);
test.sendHtmlEmail(toAddress, toName);
test.sendMultiPartEmail(toAddress, toName);
System.out.println("发送完成");
}//发送简单邮件,类似一条信息
public voidsendSimpleEmail(String toAddress, String toName) throws Exception {
SimpleEmail email= newSimpleEmail();
email.setHostName(hostName);//设置smtp服务器
email.setAuthentication(userName, password);//设置授权信息
email.setCharset("utf-8");
email.setFrom(fromAddress, fromName,"utf-8");//设置发件人信息
email.addTo(toAddress, toName, "utf-8");//设置收件人信息
email.addCc(xxx, xxx);//设置抄送
email.addBcc(xxx, xxx);//设置密送
email.setSubject("测试主题");//设置主题
email.setMsg("这是一个简单的测试!");//设置邮件内容
email.send();//发送邮件
}//发送Html内容的邮件
public voidsendHtmlEmail(String toAddress, String toName) throws Exception {
HtmlEmail email= newHtmlEmail();
email.setHostName(hostName);
email.setAuthentication(userName, password);
email.setCharset("utf-8");
email.addTo(toAddress, toName,"utf-8");
email.addCc(xxx, xxx);//设置抄送
email.addBcc(xxx, xxx);//设置密送
email.setFrom(fromAddress, fromName, "utf-8");
email.setSubject("这是一个html邮件");//设置html内容,实际使用时可以从文本读入写好的html代码
email.setHtmlMsg("
email.send();
}//发送复杂的邮件,包含附件等
public voidsendMultiPartEmail(String toAddress, String toName) throws Exception {
MultiPartEmail email= null;
email= newMultiPartEmail();
email.setHostName(hostName);
email.setAuthentication(userName, password);
email.setCharset("utf-8");
email.addTo(toAddress, toName,"utf-8");
email.addCc(xxx, xxx);//设置抄送
email.addBcc(xxx, xxx);//设置密送
email.setFrom(fromAddress, fromName, "utf-8");
email.setSubject("这是有附件的邮件");
email.setMsg("测试内容");//为邮件添加附加内容
EmailAttachment attachment = newEmailAttachment();
attachment.setPath("D:\\邮件.txt");//本地文件//attachment.setURL(new URL("http://xxx/a.gif"));//远程文件
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("描述信息");//设置附件显示名字,必须要编码,不然中文会乱码
attachment.setName(MimeUtility.encodeText("邮件.txt"));//将附件添加到邮件中
email.attach(attachment);
email.send();
}
}