目前163和qq邮箱支持SMTP协议,本文以qq邮箱为例,163邮箱和这个思路一样
场景:使用qq邮箱给xx邮箱发一条邮件,那么你一定要获得qq邮箱的授权码,在设置-账户
里找到以下内容,开启服务获得授权码,如果你已经开启了,那么点击生成授权码
获得授权码:
POM.xml中导入以下依赖:
<dependencies>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
在classpath路径下(我是src/main/resources
)新建mail.properties配置文件,配置内容如下:
email.host=smtp.qq.com
email.port=465
email.from=809476070@qq.com
username=809476070@qq.com
password=授权码
注意:
smtp.163.com
核心代码:
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.ResourceBundle;
public class EmailHelper {
private static final ResourceBundle bundle = ResourceBundle.getBundle("mail");
private static final String sendFrom = bundle.getString("email.from");
private static final String username = bundle.getString("username");
private static final String password = bundle.getString("password");
private static final String host = bundle.getString("email.host");
public static void sendEmail(String someone, String subject, String content){
Properties props = new Properties();
props.setProperty("mail.host", host);
props.setProperty("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator(){
@Override
public javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(sendFrom));
message.setRecipients(MimeMessage.RecipientType.TO,InternetAddress.parse(someone));
//message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));
try {
message.setSubject(subject);
message.setContent(content,"text/html;charset=UTF-8");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
测试代码:
import org.junit.Test;
public class test {
@Test
public void tsetemail(){
String content ="Hello,This is a test email!!!!";
//参数分别为接收者邮箱、title、内容body
EmailHelper.sendEmail("809476070@zjtlcb.com", "标题", content);
}
}