本人使用的是QQ邮箱
首先要在QQ邮箱里打开设置--账户--下方POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务开启
开启后会生成一个授权码,记下.
/** * 发送邮件 * * @param to 目标邮箱地址 * @param text 内容 * @param title 标题 * @throws MessagingException */ public static void sendMail(String to, String text, String title) throws MessagingException { Properties properties = new Properties(); // 表示SMTP发送邮件,必须进行身份验证 properties.put("mail.smtp.auth", "true"); // SMTP服务器 QQ邮箱是smtp.qq.com properties.put("mail.smtp.host", MailConstant.HOST); // 端口号 我设置的是587,QQ邮箱有提供两个端口号 properties.put("mail.smtp.port", MailConstant.PORT); // QQ邮箱账号 properties.put("mail.user", MailConstant.USER); // 16位STMP口令 授权码 properties.put("mail.password", MailConstant.PASSWORD); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // QQ邮箱账号和授权码 return new PasswordAuthentication(MailConstant.USER, MailConstant.PASSWORD); } }; // 使用环境属性和授权信息,创建邮件会话 Session mailSession = Session.getInstance(properties, authenticator); // 创建邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 message.setFrom(new InternetAddress(MailConstant.USER)); // 设置收件人的邮箱 message.setRecipient(RecipientType.TO, new InternetAddress(to)); // 设置邮件标题 message.setSubject(title); // 设置邮件的内容体 message.setContent(text, "text/html;charset=UTF-8"); // 发送邮件 Transport.send(message); }
maven
<!-- 邮件 --> <dependency> <groupId>javax.mail</groupId> <artifactId>mailapi</artifactId> <version>1.4.3</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency>
最后吐槽一下QQ邮箱,这个授权码过几天会失效要重新生成,总是要去更新授权码.