1. 程式人生 > >java利用spring提供的發郵件

java利用spring提供的發郵件

spring環境,還要引入一個jar

<!-- https://mvnrepository.com/artifact/javax.mail/com.springsource.javax.mail -->
<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>com.springsource.javax.mail</artifactId>
	<version>1.4.0</version>
</dependency>
public class EmailUtil {

    private static Properties mailProperties = PropertyLoader.getPropertyByPath("mail.properties");//封裝好的讀取配置檔案
    //沒啥內容 就不展示了

    /** PORT */25
    private static final Integer PORT = Integer.valueOf(mailProperties.getProperty("mail.sender.port").trim());

    /** host */  //smtp.sina.com
    private static final String MAIL_SMTP_HOST = mailProperties.getProperty("mail.smtp.host").trim();

    /** user_name */  //發郵件的人
    private static final String USER_NAME = mailProperties.getProperty("mail.sender.username").trim();

    /** passWord */  //密碼
    private static final String PASS_WORD = mailProperties.getProperty("mail.sender.password").trim();

    /** 初始化郵件 */
    private static final JavaMailSenderImpl mailSend = createMailSender();
    /**
     * daidong
     * 
     * @param orgName
     *            郵件名稱
     * @param letter
     *            郵件主體
     * @param email
     *            郵箱地址
     * @return Result
     */
    public static void sendEmail(String orgName, String letter, String email) throws MessagingException {
        if (StringUtils.isBlank(orgName) || StringUtils.isBlank(letter) || StringUtils.isBlank(email)) {
            return;
        }
        //進行配置
        MimeMessage mimeMessage = mailSend.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        mimeMessageHelper.setFrom(USER_NAME);
        mimeMessageHelper.setTo(email);
        mimeMessageHelper.setSubject(orgName);
        mimeMessageHelper.setText("",letter);//第一個引數為純文字,第二個為html
        mailSend.send(mimeMessage);
    }
    //配置
    private static JavaMailSenderImpl createMailSender(){
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(MAIL_SMTP_HOST);
        sender.setPort(PORT);
        sender.setUsername(USER_NAME);
        sender.setPassword(PASS_WORD);
        sender.setDefaultEncoding("utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout","25000");
        p.setProperty("mail.smtp.auth","true");//是否需要密碼,一般都為true
        sender.setJavaMailProperties(p);
        return sender;
    }
}