一个MailClient代码

public class MailClient {

@Autowired

private MailConfig mailConfig;

public boolean sendEmail(String target, String title, String content) {

    Properties props = new Properties();

    // 开启debug调试

    props.setProperty("mail.debug", "false");

    // 发送服务器需要身份验证

    props.setProperty("mail.smtp.auth", "true");

    props.setProperty("mail.transport.protocol", mailConfig.getProtocol());

    props.setProperty("mail.smtp.port", mailConfig.getPort());

    props.setProperty("mail.smtp.host", mailConfig.getServer());

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.smtp.socketFactory.port", mailConfig.getPort());

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

    props.put("mail.smtp.socketFactory.fallback", "false");

    SimpleAuthenticator simpleAuthenticator = new SimpleAuthenticator(mailConfig.getAccount(),

            mailConfig.getPassword());

    // 设置环境信息

    Session session = Session.getDefaultInstance(props, simpleAuthenticator);

    // 创建邮件对象

    Message message = new MimeMessage(session);

    try {

        message.setSubject(title);

        // 设置邮件内容

        Multipart mainPart = new MimeMultipart();

        // 创建一个包含HTML内容的MimeBodyPart

        BodyPart html = new MimeBodyPart();

        // 设置HTML内容

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

        mainPart.addBodyPart(html);

        // 将MiniMultipart对象设置为邮件内容

        message.setContent(mainPart);

        // 设置发件人

        message.setFrom(new InternetAddress(mailConfig.getAccount()));

        Transport transport = session.getTransport();

        // 连接邮件服务器

        transport.connect(mailConfig.getAccount(), mailConfig.getPassword());

        // 发送邮件

        transport.sendMessage(message, new Address[] { new InternetAddress(target) });

        // 关闭连接

        transport.close();

        return true;

    } catch (Exception e) {

        return false;

    }

}

}

你可能感兴趣的:(一个MailClient代码)