spring java mail freemarker 发送邮件

<!-- 邮件发送器 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${javax.mail.host}" />
    <property name="username" value="${javax.mail.username}" />
    <property name="password" value="${javax.mail.password}" />
    <property name="protocol" value="${javax.mail.protocol}" />
    <property name="defaultEncoding" value="${javax.mail.defaultEncoding}" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">${javax.mail.smtp.auth}</prop>
            <prop key="mail.smtp.starttls.enable">${javax.mail.smtp.starttls.enable}</prop>
        </props>
    </property>
</bean>

<!-- freeMarkerConfigurer -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/WEB-INF/tpl/" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>

public void sendMimeMessage(String from, String to, String subject, String text, File... files){
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper;
    try {
        mimeMessageHelper = new MimeMessageHelper(mimeMessage, true , "utf-8");
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(text, true);
        for(int i=0;i<files.length;i++){
            mimeMessageHelper.addAttachment(files[i].getName(), files[i]);
        }
        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注