新网Logo
首页>邮箱资讯>

Java-使用JavaMail发送一封邮件给用户邮箱功能实现

登录 注册

Java-使用JavaMail发送一封邮件给用户邮箱功能实现

  • 来源:新网
  • 更新日期:2018-03-13

摘要:<—————————–start—————————–> 通过javamail发送一封邮件: 较早前,我已经编写好了发送邮件的工具类MailUtils。有以下要点需要注意: ① 发件箱的邮件服务器地址。 ② 发件箱账号。 ③ 邮箱授权码,在所使用的邮箱后台管理中设置。 ④ 激活邮件的地址。public class MailUtils { private static

<—————————–start—————————–>
通过javamail发送一封邮件:

t013d2450e5daf82b34.jpg
较早前,我已经编写好了发送邮件的工具类MailUtils。有以下要点需要注意:


① 发件箱的邮件服务器地址。
② 发件箱账号。
③ 邮箱授权码,在所使用的邮箱后台管理中设置。
④ 激活邮件的地址。

public class MailUtils { private static String smtp_host = "smtp.163.com"; // 网易 private static String username = "niwotaxuexiba_search@163.com"; // 邮箱账户 private static String password = "niwotaxuexiba123"; // 邮箱授权码 private static String from = "niwotaxuexiba_search@163.com"; // 使用当前账户 public static String activeUrl = "http://localhost:9003/bos_fore/customer_activeMail"; public static void sendMail(String subject, String content, String to) { Properties props = new Properties(); props.setProperty("mail.smtp.host", smtp_host); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.setRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setContent(content, "text/html;charset=utf-8"); Transport transport = session.getTransport(); transport.connect(smtp_host, username, password); transport.sendMessage(message, message.getAllRecipients()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("邮件发送失败..."); } } //测试代码:测试邮件能否发送成功 public static void main(String[] args) { sendMail("测试邮件", "你好,你我他学习吧", "niwotaxuexiba_search@163.com"); } }

在sendMail(参数①,参数②,参数③)方法中设置三个参数:
① 邮件主题;
② 邮件内容;
③ 目标邮箱账户(发给谁)。
需要在pom.xml文件中添加javamail邮件发送工具包的坐标。添加完依赖后重新install以下。
<—————————–end—————————–>