摘要
java写的发送邮件功能,以qq邮箱作为发件人,收件邮件没有特殊要求。
需要注意的是发件qq邮箱需要开启POP3/STMP服务并生成授权码,发送邮件时把授权码当成密码使用。
maven pom
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
发送邮件的方法
/**
* 发送QQ邮件
* @param from 发件人
* @param to 收件人
* @param password 密码/授权码
* @param subject 主题
* @param content 内容
* @param debug 是否打印调试信息
* @throws Exception
*/
public void send(String from, String to, String password, String subject, String content, boolean debug) throws Exception{
Properties properties = new Properties();
if(debug){
properties.setProperty("mail.debug", "true");
}
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.host", "smtp.qq.com");
properties.put("mail.smtp.ssl.enable", true);
MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
Session session = Session.getInstance(properties);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(content);
Transport transport = session.getTransport();
transport.connect(from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
运行结果
/**
* from
*/
public static final String SENDER_ADDRESS = "779518947@qq.com";
/**
* to
*/
public static final String RECIEVE_ADDRESS = "1040434468@qq.com";
/**
* auth code
*/
public static final String AUTH_CODE = "aguwwkbojsct****";
@Test
public void test() throws Exception{
send(SENDER_ADDRESS, RECIEVE_ADDRESS, AUTH_CODE, "test", "测试", true);
}