关于java发送email

转载:https://blog.csdn.net/qq_32371887/article/details/72821291

1:使用JavaMail发送邮件

 // 1.创建一个程序与邮件服务器会话对象 Session
 Properties props = new Properties();
 props.setProperty("mail.transport.protocol", "SMTP");
 props.setProperty("mail.smtp.host", "smtp.163.com");
 props.setProperty("mail.smtp.port", "25");
 // 指定验证为true
 props.setProperty("mail.smtp.auth", "true");
 props.setProperty("mail.smtp.timeout","1000");
 // 验证账号及密码,密码需要是第三方授权码
 Authenticator auth = new Authenticator() {
 public PasswordAuthentication getPasswordAuthentication({
    return new PasswordAuthentication("*******@163.com", "*******");
            }
        };
 Session session = Session.getInstance(props, auth);

// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
// 设置发送者
message.setFrom(new InternetAddress("*******@163.com"));
// 设置发送方式与接收者
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
// 设置主题
message.setSubject("邮件发送测试");
// 设置内容
message.setContent(emailMsg, "text/html;charset=utf-8");

// 3.创建 Transport用于将邮件发送
Transport.send(message);

2:我用的是spring框架,spring 封装了一个简单易用的关于邮件发送的工具类JavaMailSenderImpl ,所以可以用JavaMailSenderImpl 来实现邮件发送。

public class MailService {
    private static final String HOST = "smtp.163.com";
    private static final Integer PORT = 25;
    private static final String USERNAME = "*******@163.com";
    private static final String PASSWORD = "*******";
    private static final String EMAILFORM = "*******@163.com";
    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", "25000");
        p.setProperty("mail.smtp.auth", "false");
        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 发送邮件
     *
     * @param to 接受人
     * @param subject 主题
     * @param html 发送内容
     * @throws MessagingException 异常
     * @throws UnsupportedEncodingException 异常
     */
    public static void sendHtmlMail(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, "系统名称");
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        mailSender.send(mimeMessage);
    }
}

 

posted @ 2018-07-16 16:31  刘凌枫羽  阅读(213)  评论(0编辑  收藏  举报