邮件工具类,使用java发送邮件,常用于邮箱激活场景,用于发送的账号需要进行以下配置:
- 以QQ邮箱为例,需要在设置->账户下打开POP3和IMAP服务(也可以直接全开),这样才能第三方登录邮箱(Java中登录也算第三方)
- 开启的时候会获取一个授权码(没记下来就再次关闭打开,每次都不一样的,但是每个都有效)
- 直接复制即可食用,就只有一个静态方法调用即可,参数已注明在注释中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties;
public final class MailUtils { private static final String USER = "975504808@qq.com"; private static final String PASSWORD = "刚刚说的授权码";
public static boolean sendMail(String to, String text, String title){ try { final Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.user", USER); props.put("mail.password", PASSWORD);
Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; Session mailSession = Session.getInstance(props, authenticator); MimeMessage message = new MimeMessage(mailSession); String username = props.getProperty("mail.user"); InternetAddress form = new InternetAddress(username); message.setFrom(form);
InternetAddress toAddress = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(title);
message.setContent(text, "text/html;charset=UTF-8"); Transport.send(message); return true; }catch (Exception e){ e.printStackTrace(); } return false; } }
|
后序的工具类我想做成文件下载而不是贴代码…看下什么时候有空再说(拖延症晚期)