使用java发送邮件
准备工作:
下载两个发送邮件的包并导入到java:activation-1.1.1.jar,javax.mail.jar;
创建一个用于发送邮件的类
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
public class mail {
private static MimeMessage message;
//在发送验证码邮件后保存一份验证码,用于判定验证码是否匹配
public static String JudgeCode;
//to 为你要发送到的邮箱的地址
public static void sendEmail(String to) throws MessagingException {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// QQ邮箱服务器
String smtpHost = "smtp.qq.com";
// 邮箱用户名,即QQ账号(自定义)
final String username = "邮箱用户名";
// 邮箱授权码(自定义)
final String password = "邮箱授权码";
// 自己的邮箱(自定义)
final String from = "自己的邮箱";
// 要发送的邮箱地址(自定义)
String toAddress = to;
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(toAddress)};
message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, addresses);
message.setSubject("验证码");// 发送标题(自定义)
message.setSentDate(new Date());
message.setText(generateVerificationCode(5));// 发送内容(自定义)
transport = session.getTransport("smtp");
transport.connect(smtpHost, username, password);
transport.send(message);
System.out.println("邮件发送成功");
transport.close();
}
//用于生成验证码的方法
//生成的方法为从26个大小写字母和数字中随机选中指定长度的字符然后保存验证码
private static String generateVerificationCode(int length) {
String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder verificationCode = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
verificationCode.append(charSet.charAt(random.nextInt(charSet.length())));
}
JudgeCode = verificationCode.toString();
return verificationCode.toString();
}
}
然后我们只要通过类名来调用这个类中的sendEmail(to)静态方法就行了。