java mail

package com.boventech.learning.test;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 邮件测试
 * @author
 *
 */
public class MailTest {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MailTest.class);
	
	private static final String HOST = "smtp.gmail.com";
	
	private static final int PORT = 587;
	
	private static final String USERNAME = "xxx";

	private static final String PASSWORD = "xx";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String to = "764503410@qq.com";
        String title = "主题";
        String content = "内容";
        sendMail(to, title, content);
	}
	
	/**
	 * 发送邮件
	 * @param to
	 * @param title
	 * @param content
	 * @return
	 */
	public static boolean sendMail(String to,String title,String content){
		final String _to = to;
        final String _title = title;
        final String _content = content;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    sendHtmlMail(_to, _title, _content);
                } catch (MessagingException e) {
                    String msg = String.format("Error when send mail", _to);
                    LOGGER.error(msg, e);
                }
            }
        }).start();
        return true;
	}
	
	/**
	 * 邮件配置
	 * @param to
	 * @param subject
	 * @param htmlContent
	 * @throws MessagingException
	 */
	private static void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(HOST);
		mailSender.setPort(PORT);
		mailSender.setUsername(USERNAME);
		mailSender.setPassword(PASSWORD);
		Properties javaMailProperties = new Properties();
		javaMailProperties.setProperty("mail.transport.protocol", "smtp");
		javaMailProperties.setProperty("mail.smtp.auth", "true");
		javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
		javaMailProperties.setProperty("mail.debug", "false");
		mailSender.setJavaMailProperties(javaMailProperties);
		MimeMessage message = mailSender.createMimeMessage();
        
        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setTo(to);
        helper.setSubject(subject);

        // use the true flag to indicate the text included is HTML
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }
	
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值