JAVAMAIL试用google邮箱发送邮件

这里的Demo简单来,希望给第一次试用的你帮助。
. 1,试用网易邮箱发送邮件:

  //网易
public static Session getNetEasySession() {
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.host", "smtp.163.com");
    props.setProperty("mail.smtp.port", "25");
    props.setProperty("mail.smtp.auth", "true");

    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(FROM, "panda0920");
        }
    });
    return session;
}

. 2,google邮箱发送邮件:

    public static Session getGMailSession() {
    Properties props = new Properties();
//        props.put("mail.smtp.host", "smtp.gmail.com");
//        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.smtp.socketFactory.fallback", "false");
//        props.put("mail.smtp.port", "465");
//        props.put("mail.smtp.socketFactory.port", "465");
//        props.put("mail.smtp.auth", "true");

        //当前用这种方式。
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override  
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, "panda0920");
            }
        });  
        return session;  
    }

来一个main测试下

private static final String FROM = "[email protected]";

   public static void sendAccountActivateEmail(String email,String vaildCode)throws Exception {
        Session session = getGMailSession();
            MimeMessage message = new MimeMessage(session);
            message.setSubject("test");
            message.setSentDate(new Date());
            message.setFrom(new InternetAddress(FROM));            message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
//            message.setContent("test11111",","text/html;charset=utf-8");            // 发送邮件  
            Transport.send(message);
    }
 public  static void  main(String args[]){
        try {           sendAccountActivateEmail("[email protected]","test");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

注意项:不管是网易还是谷歌邮箱都需要登录邮箱设置安全登录之类的,比如:

JAVAMAIL试用google邮箱发送邮件_第1张图片JAVAMAIL试用google邮箱发送邮件_第2张图片

你可能感兴趣的:(工具使用)