JAVAMAIL试用google邮箱发送邮件

来源:互联网 发布:优化web性能 编辑:程序博客网 时间:2024/06/07 05:29

这里的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 = "xxxxxx@gmail.com";   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("99999999@qq.com","test");        } catch (Exception e) {            e.printStackTrace();        }    }

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

这里写图片描述这里写图片描述

原创粉丝点击