1、在eclipse中创建项目,并把javax.amil.jar(1.6.2)和commons-email-1.1,jar复制到项目lib文件中,jar包可网上自行下载,也可联系本站提供
或者引入:
commons-email
commons-email
1.1
com.sun.mail
smtp
1.6.2
2、打开qq邮件首页,找到设置>
账户>
找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,找到IMAP/SMTP服务,点击开启
通过手机短信验证获取授权码
3、代码import com.sun.net.ssl.internal.ssl.Provider;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
public class MailSender {
private static MimeMessage message;
public static void main(String[] args) throws MessagingException {
Security.addProvider(new Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//QQ邮箱服务器
String smtpHost="smtp.qq.com";
//邮箱用户名,即QQ账号
final String username = "1129517721";
//邮箱授权码
final String password = "ttypodnvoseywwbaai";//用自己的,别用我的,这个号是我瞎编的,为了。。。。
//要发送到的邮箱
String to = "3117075055@qq.com";
//自己的邮箱
String from = "1129517721@qq.com";
Transport transport;
Properties props = new Properties();
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.auth", "true");
props.put("mail.smtp.host",smtpHost);
props.put("mail.smtp.username", username);
props.put("mail.smtp.password", password);
Session session = Session.getDefaultInstance(props, new Authenticator() {
//身份认证
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
InternetAddress[] addresses = {new InternetAddress(to)};
message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,addresses);
message.setSubject("JavaMail测试");
message.setSentDate(new Date());
message.setText("JavaMail发送邮件成功!");
transport = session.getTransport("smtp");
transport.connect(smtpHost, username, password);
transport.send(message);
System.out.println("email has been sent");
}
}