一.进入QQ邮箱获取授权码 1.进入QQ邮箱点击,点击左上角的设置
2.点击账户 然后拉下来,开启SMTP 服务,可以获取授权码,复制下来。 二.maven依赖
<dependency>
<groupId >com.sun.mail</groupId >
<artifactId >javax.mail</artifactId >
<version >1.5.5</version >
</dependency>
<dependency >
<groupId >javax.mail </groupId >
<artifactId >mail</artifactId >
<version >1.4.5</version >
</dependency >
三.java发送qq邮箱工具类,使用个人邮箱发送
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailUtil{
public static void sendEmail(String toEmail,String fromEmail,
final String authEmail,final String authPaw,
String title,String text){
String to = toEmail;
String from = fromEmail;
String host = "smtp.qq.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
Session session = Session.getInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(authEmail, authPaw);
}
});
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(title);
message.setContent(text, "text/html;charset=UTF-8");
Transport.send(message);
System.out.println("Sent email successfully...");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
EmailUtil.sendEmail("XXXXXX(收件人邮箱)@qq.com","XXXXXX(发件人邮箱)@qq.com","(授权邮箱,一般就是填发件人邮箱)XXXXX@qq.com","发件人的QQ邮箱里的授权码","邮件名","邮件内容");
}
}
|