java-mail测试

java 发送邮箱的两种方式:

方式一JavaMail:

util:
public class MailUtils {

    /**
     * 
     * @param email 邮件发送给谁
     * @param emailMsg 邮件的内容
     * 
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendMail(String email, String emailMsg)
            throws AddressException, MessagingException {
        // 1.创建一个程序与邮件服务器会话对象 Session
        //主要说明是什么邮箱服务器,使用什么协议去发邮件
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "SMTP"); //发送邮件的协议
        props.setProperty("mail.host", "smtp.126.com"); // 邮件的服务器地址
        props.setProperty("mail.smtp.auth", "true");// 指定验证为true

        // 创建验证器   用什么手段什么口令,什么验证码去登录上面说的那个邮箱服务器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("supliulonghua", "这个126邮箱的授权码");//授权码
            }
        };
        
        //创建连接对象 ,主要是跟发送邮件的服务器形成对话。 
        Session session = Session.getInstance(props, auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress("[email protected]")); // 设置发送者

        message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

        message.setSubject("激活邮件");

        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.创建 Transport用于将邮件发送
        Transport.send(message);
    }
}
controller:
@Controller
public class SendMailController
{

  @RequestMapping("sendMail")
  @ResponseBody
  public String sendMail(){
    try
    {
      String emailMsg = "信息内容";
      String email = "[email protected]";
      MailUtils.sendMail(email, emailMsg);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    
    return "发送邮件成功";
  }
  
}

pom:

        
        
            javax.mail
            mail
            1.5.0-b01
        

测试结果:

java-mail测试_第1张图片
10841f88136ac4dacae5c7407dbf544.png

设置授权码:

java-mail测试_第2张图片
95d4229c6c57f3a89575564172f012b.png

方式二JavaMailSenderImpl:

properties:
#服务器
mailHost=smtp.126.com
#端口号 这个可以不用,不写默认
mailPort=25
#邮箱账号
[email protected]
#邮箱授权码
mailPassword=授权码
#时间延迟
mailTimeout=25000
#发送人
[email protected]
#发送人名称
personal = 最终幻想126
加载config:
public class MailConfig
{

  private static final String PROPERTIES_DEFAULT = "mailConfig.properties";
  public static String host;
  public static Integer port;
  public static String userName;
  public static String passWord;
  public static String emailForm;
  public static String timeout;
  public static String personal;
  public static Properties properties;
  static{
      init();
  }

  /**
   * 初始化
   */
  private static void init() {
      properties = new Properties();
      try{
          InputStream inputStream = MailConfig.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT);
          //如果properties文件中有汉子,则汉字会乱码,设置编码格式。  
          InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 
          properties.load(inputStreamReader);
          inputStreamReader.close();
          
          host = properties.getProperty("mailHost");
          port = Integer.parseInt(properties.getProperty("mailPort"));
          userName = properties.getProperty("mailUsername");
          passWord = properties.getProperty("mailPassword");
          emailForm = properties.getProperty("mailFrom");
          timeout = properties.getProperty("mailTimeout");
          personal = properties.getProperty("personal");
      } catch(IOException e){
          e.printStackTrace();
      }
  }
}
util
public class SpringJavaMailSenderUtil
{
  private static final String HOST = MailConfig.host;
  private static final Integer PORT = MailConfig.port;
  private static final String USERNAME = MailConfig.userName;
  private static final String PASSWORD = MailConfig.passWord;
  private static final String emailForm = MailConfig.emailForm;
  private static final String timeout = MailConfig.timeout;
  private static final String personal = MailConfig.personal;
  private static JavaMailSenderImpl mailSender = createMailSender();
  /**
   * 邮件发送器
   *
   * @return 配置好的工具
   */
  private static JavaMailSenderImpl createMailSender() {
      JavaMailSenderImpl sender = new JavaMailSenderImpl();
      sender.setHost(HOST);
      sender.setPort(PORT);
      sender.setUsername(USERNAME);
      sender.setPassword(PASSWORD);
      sender.setDefaultEncoding("Utf-8");
      Properties p = new Properties();
      p.setProperty("mail.smtp.timeout", timeout);
      p.setProperty("mail.smtp.auth", "false");
      sender.setJavaMailProperties(p);
      return sender;
  }

  /**
   * 发送邮件
   *
   * @param to 接受人
   * @param subject 主题
   * @param html 发送内容
   * @throws MessagingException 异常
   * @throws UnsupportedEncodingException 异常
   */
  public static void sendMail(String to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
      MimeMessage mimeMessage = mailSender.createMimeMessage();
      // 设置utf-8或GBK编码,否则邮件会有乱码
      MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
      messageHelper.setFrom(emailForm, personal);//这边可以显示发送方名称
      messageHelper.setTo(to);
      messageHelper.setSubject(subject);
      messageHelper.setText(html, true);
      mailSender.send(mimeMessage);
  }
}
controller
@Controller
public class SendMailController
{

  @RequestMapping("sendJavaMailSender")
  @ResponseBody
  public String sendMailJavaMailSender(){
    try
    {
      String emailMsg = "警告信息内容";
      String email = "[email protected]";
      SpringJavaMailSenderUtil.sendMail(email, "警告!!!!", emailMsg);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    
    return "发送邮件成功";
  }
  
}

pom

        
            org.springframework.boot
            spring-boot-starter-mail
        

结果同上。

以上,谢谢!

你可能感兴趣的:(java-mail测试)