发邮件

发邮件

一 普通代码

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");//指定邮件的发送服务器地址
        props.put("mail.port", "165");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");

        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getInstance(props);//得到Session
        session.setDebug(true);//代表启用debug模式,可以在控制台输出smtp协议应答的过程


        //创建一个MimeMessage格式的邮件
        MimeMessage message = new MimeMessage(session);

        //设置发送者
        Address fromAddress = new InternetAddress("xxxxxxx@163.com");//邮件地址
        message.setFrom(fromAddress);//设置发送的邮件地址
        //设置接收者
        Address toAddress = new InternetAddress("xxxxxx@qq.com");//要接收邮件的邮箱
        message.setRecipient(Message.RecipientType.TO, toAddress);//设置接收者的地址

        //设置邮件的主题
        message.setSubject("test");
        //设置邮件的内容
        message.setText("it"s a test mail");
        //保存邮件
        message.saveChanges();


        //得到发送邮件的服务器(这里用的是smtp服务器)
        Transport transport = session.getTransport("smtp");

        //发送者的账号连接到smtp服务器上  @163.com可以不写
        transport.connect("smtp.163.com","xxxxxx.com","xxxxxxxx");
        //发送信息
        transport.sendMessage(message, message.getAllRecipients());
        //关闭服务器通道
        transport.close();

 

二 Spring

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");//指定邮件的发送服务器地址
        props.put("mail.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");

        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");


        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setJavaMailProperties(props);

        mailSender.setUsername("xxxxxx@163.com");
        mailSender.setPassword("xxxxxxx");  // 需要使用授权码

        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom("xxxxx@163.com");
        smm.setTo("xxxxxxxx@dingtalk.com");
        smm.setSubject("test");
        smm.setText("你好");
        mailSender.send(smm);