1、简单介绍
本文主要是做一个笔记,记录一下我今天测试的java发送邮件。我用163邮箱发送邮件成功了,但是用QQ邮箱发送邮件报SSL的错误,并且我在云服务器上用postfix发送邮件也成功了。所以,本文主要记录用163邮箱和Centos7的postfix发送邮件。
2、163邮箱发送邮件
(说明:以下代码摘自网络后修改的,非本人原创)
(1)准备工作
打开163的POP/SMTP服务
(2)代码如下:
package com.sqb.mail;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendMail {
private String username = null;
private String password = null;
private Authenticator auth = null;
private MimeMessage mimeMessage =null;
private Properties pros = null;
private Multipart multipart = null;
private BodyPart bodypart= null;
/**
* 初始化账号密码并验证
* 创建MimeMessage对象
* 发送邮件必须的步骤:1
* @param username
* @param password
*/
public SendMail(String username,String password){
this.username = username;
this.password = password;
}
/**
* 初始化MimeMessage对象
* 发送邮件必须的步骤:3
*/
public void initMessage(){
this.auth = new Email_Autherticator();
Session session = Session.getDefaultInstance(pros,auth);
session.setDebug(true); //设置获取 debug 信息
mimeMessage = new MimeMessage(session);
}
/**
* 设置email系统参数
* 接收一个map集合key为string类型,值为String
* 发送邮件必须的步骤:2
* @param map
*/
public void setPros(Map<String,String> map){
pros = new Properties();
for(Map.Entry<String,String> entry:map.entrySet()){
pros.setProperty(entry.getKey(), entry.getValue());
}
}
/**
* 验证账号密码
* 发送邮件必须的步骤
* @author Administrator
*
*/
public class Email_Autherticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
}
/**
* 设置发送邮件的基本参数(去除繁琐的邮件设置)
* @param sub 设置邮件主题
* @param text 设置邮件文本内容
* @param rec 设置邮件接收人
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{
mimeMessage.setSubject(sub);
mimeMessage.setText(text);
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
mimeMessage.setSentDate(new Date());
mimeMessage.setFrom(new InternetAddress(username,username));
}
/**
* 设置主题
* @param subject
* @throws MessagingException
*/
public void setSubject(String subject) throws MessagingException{
mimeMessage.setSubject(subject);
}
/**
* 设置日期
* @param date
* @throws MessagingException
*/
public void setDate(Date date) throws MessagingException{
mimeMessage.setSentDate(new Date());
}
/**
* 设置邮件文本内容
* @param text
* @throws MessagingException
*/
public void setText(String text) throws MessagingException{
mimeMessage.setText(text);
}
/**
* 设置邮件头部
* @param arg0
* @param arg1
* @throws MessagingException
*/
public void setHeader(String arg0,String arg1) throws MessagingException{
mimeMessage.setHeader(arg0, arg1);
}
/**
* 设置邮件接收人地址 <单人发送>
* @param recipient
* @throws MessagingException
*/
public void setRecipient(String recipient) throws MessagingException{
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
/**
* 设置邮件接收人地址 <多人发送>
* @param list
* @throws MessagingException
* @throws AddressException
*/
public String setRecipients(List<String> recs) throws AddressException, MessagingException{
if(recs.isEmpty()){
return "接收人地址为空!";
}
//下面这3行是原作者的,不行,使得发送时报554错误
// for(String str:recs){
// mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
// }
//以下5行是我写的
int size = recs.size();
Address[] addresses = new InternetAddress[size];
for(int i=0; i<size; i++){
addresses[i] = new InternetAddress(recs.get(i));
}
//原作者用addRecipient报错,我改为setRecipients成功群发。
mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
return "加入接收人地址成功!";
}
/**
* 设置邮件接收人地址 <多人发送>
* @param StringBuffer<parms,parms2,parms.....>
* @throws MessagingException
* @throws AddressException
*/
@SuppressWarnings("static-access")
public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{
if(sb==null||"".equals(sb)){
return "字符串数据为空!";
}
Address[] addresses = new InternetAddress().parse(sb.toString());
mimeMessage.addRecipients(Message.RecipientType.TO, addresses);
return "收件人加入成功";
}
/**
* 设置邮件发送人的名字
* @param from
* @throws UnsupportedEncodingException
* @throws MessagingException
*/
public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{
mimeMessage.setFrom(new InternetAddress(username,from));
}
/**
* 发送邮件<单人发送>
* return 是否发送成功
* @throws MessagingException
*/
public String sendMessage() throws MessagingException{
Transport.send(mimeMessage);
return "success";
}
/**
* 设置附件<单个附件>
* @param file 发送文件的路径
*/
public void setMultipart(String file) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
multipart.addBodyPart(writeFiles(file));
mimeMessage.setContent(multipart);
}
/**
* 设置附件<添加多附件>
* @param fileList<接收List集合>
* @throws MessagingException
* @throws IOException
*/
public void setMultiparts(List<String> fileList) throws MessagingException, IOException{
if(multipart==null){
multipart = new MimeMultipart();
}
for(String s:fileList){
multipart.addBodyPart(writeFiles(s));
}
mimeMessage.setContent(multipart);
}
/**
* 发送文本内容,设置编码方式
* <方法与发送附件配套使用>
* <发送普通的文本内容请使用setText()方法>
* @param s
* @param type
* @throws MessagingException
*/
public void setContent(String s,String type) throws MessagingException{
if(multipart==null){
multipart = new MimeMultipart();
}
bodypart = new MimeBodyPart();
bodypart.setContent(s, type);
multipart.addBodyPart(bodypart);
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
}
/**
* 读取附件
* @param filePath
* @return
* @throws IOException
* @throws MessagingException
*/
public BodyPart writeFiles(String filePath)throws IOException, MessagingException{
File file = new File(filePath);
if(!file.exists()){
throw new IOException("文件不存在!请确定文件路径是否正确");
}
bodypart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(dataSource));
//文件名要加入编码,不然出现乱码
bodypart.setFileName(MimeUtility.encodeText(file.getName()));
return bodypart;
}
}
package com.sqb.mail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
public class TestSend
{
public static void main(String[] args) throws MessagingException, IOException
{
myTestSendBy163();
//myTestSendByQQ(); //用QQ邮箱发会报错javax.net.ssl.SSLException
}
public static void myTestSendBy163() throws MessagingException, IOException{
Map<String,String> map= new HashMap<String,String>();
SendMail mail = new SendMail("sqb@163.com","cghx授权码");163邮箱和授权码
map.put("mail.smtp.host", "smtp.163.com");
map.put("mail.smtp.auth", "true");
map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
map.put("mail.smtp.port", "994");
map.put("mail.smtp.socketFactory.port", "994");
mail.setPros(map);
mail.initMessage();
/*
* 添加收件人有三种方法:
* 1,单人添加(单人发送)调用setRecipient(str);发送String类型
* 2,多人添加(群发)调用setRecipients(list);发送list集合类型
* 3,多人添加(群发)调用setRecipients(sb);发送StringBuffer类型
*/
/*
* 测试单人收件-成功测试发送于2016-12-29
*/
String defaultStr = "11@qq.com";//可能要在垃圾箱里面查看邮件
mail.setRecipient(defaultStr);
mail.setSubject("测试邮箱");
mail.setText("我是学生,这是邮件内容");
mail.setDate(new Date());
mail.setFrom("MY");
System.out.println(mail.sendMessage());
System.out.println("发送完成");
/*
* 测试多人收件-list-成功测试发送于2016-12-29,但是发第2次时就报554,可能是被163认为在群发垃圾邮件而拦截了,也可能是群发次数限制,邮件发送数限制等等。
*/
/*List<String> list = new ArrayList<String>();
list.add("11030@qq.com");
list.add("2974@qq.com");
list.add("hdx@163.com");
mail.setRecipients(list);
mail.setSubject("测试邮箱1223");
mail.setText("我是学生,这是邮件内容1213");
mail.setDate(new Date());
mail.setFrom("MY");
System.out.println(mail.sendMessage());
System.out.println("发送完成");*/
/*
* 测试多人收件-sb,失败,可能已经群发过了,被163拦截了群发
*/
/*String defaultStr = "11030@qq.com,297@qq.com";
StringBuffer sb = new StringBuffer();
sb.append(defaultStr);
mail.setRecipients(sb);
mail.setSubject("测试邮箱StringBuffer群发");
mail.setText("我是学生,这是邮件内容");
mail.setDate(new Date());
mail.setFrom("MY");
System.out.println(mail.sendMessage());
System.out.println("发送完成");*/
/*
* 测试单人接收邮件-测试成功与2016-12-29
*/
/*String defaultStr = "1103@qq.com";//可能要在垃圾箱里面查看邮件
mail.setRecipient(defaultStr);
mail.setSubject("测试邮箱");
mail.setContent("测试发送附件", "text/html; charset=UTF-8");
mail.setDate(new Date());
mail.setFrom("MY");
mail.setMultipart("D:1.jpg"); //文件在D盘下,注意":"后面没有\\的,如果放到某个目录下我知道怎么写路径
System.out.println(mail.sendMessage());
System.out.println("发送完成");*/
/*
* 测试单人接收多个附件-测试失败,报错554
*/
/*String defaultStr = "11030@qq.com";//可能要在垃圾箱里面查看邮件
mail.setRecipient(defaultStr);
mail.setSubject("测试发送附件");
mail.setContent("测试发送附件", "text/html; charset=UTF-8");
mail.setDate(new Date());
mail.setFrom("MY");
List<String> fileList = new ArrayList<String>();
fileList.add("D:1.jpg");
fileList.add("D:2.zip");
mail.setMultiparts(fileList);
System.out.println(mail.sendMessage());
System.out.println("发送完成");*/
}
public static void myTestSendByQQ() throws MessagingException, IOException{
Map<String,String> map= new HashMap<String,String>();
SendMail mail = new SendMail("11030@qq.com","cghxg");邮箱和授权码
map.put("mail.smtp.host", "smtp.qq.com");
map.put("mail.smtp.auth", "true");
map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
map.put("mail.smtp.port", "587");
map.put("mail.smtp.socketFactory.port", "587");
mail.setPros(map);
mail.initMessage();
/*
* 测试单人收件-失败,QQ邮箱报错Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
*/
String defaultStr = "sqb@163.com";//可能要在垃圾箱里面查看邮件
mail.setRecipient(defaultStr);
mail.setSubject("测试邮箱");
mail.setText("我是学生,这是邮件内容");
mail.setDate(new Date());
mail.setFrom("MY");
System.out.println(mail.sendMessage());
System.out.println("发送完成");
}
}
3、云服务器Centos7的postfix发送邮件
(1)搭建postfix,请参考http://www.cnblogs.com/dudu/archive/2012/12/12/linux-postfix-mailserver.html
(2)请在上一步完成之后再往下操作,代码如下:
public static void sendMail(String address, String from, String subject, String content) throws MessagingException {
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.host", "localhost");
prop.setProperty("mail.smtp.auth", "true");
prop.setProperty("mail.debug", "true");
Session session = Session.getInstance(prop);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(RecipientType.TO, new InternetAddress[]{new InternetAddress(address)});
msg.setSubject(subject);
msg.setText(content);
Transport trans;
trans = session.getTransport();
trans.connect("aa", "123");//这里可以随便填,因为端口25不用验证,但是connect函数还是得有,否则编译不通过。
trans.sendMessage(msg, msg.getAllRecipients());
System.out.println("complete");
}
4、简单总结
QQ邮箱没有测试成功发邮件,如果你的jdk是1.5或1.5以下,需要在百度搜 Java mail去官网下载javamail的jar包。