Java使用Spring的JavaMailSenderImpl發送Email

spring-context.xml配置

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <!-- 發送服務器,根據當前使用的郵件服務商決定 -->
        <property name="host" value="smtp.exmail.qq.com"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 發送郵件的用戶名密碼 -->
        <property name="username" value="[email protected]"/>
        <property name="password" value="*******"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <!-- 此處不建議設置超時時間,設置了可能導致郵件服務商返回消息的延遲而導致程序拋出異常,以下代碼send方法返回false,但是實際上郵件已經發出去了的問題,如果程序需要性能考慮,又不着急需要郵件發送那個的結果,可以考慮使用異步發送郵件(本人就是這樣做的,剛開始程序會卡這兒很久,異步之後就好了) -->
                <!--<prop key="mail.smtp.timeout">1000</prop>-->
                <!-- 使用SSL加密端口,基於安全考慮 -->
                <prop key="mail.smtp.port">465</prop>

                <prop key="mail.smtp.socketFactory.port">465</prop>
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
            </props>
        </property>
    </bean>

    <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="[email protected]"/>
        <!-- 接收郵件的郵箱 -->
        <property name="to" value="[email protected]"/>
        <!-- subject是設置郵件標題,剛開始在這兒設置,發現到了服務器上就中文亂碼,如果非要在這個地方配置,可以將配置文件中的中文轉成unicode碼,就不會亂碼了(但是這樣別人就看不懂了,不利於後期代碼維護,個人不建議) -->
        <!--<property name="subject" value="${mail.subject}"/>-->
    </bean>

    <!-- 從Java代碼讀取配置文件值的配置 -->
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:config.properties</value>
            </list>
        </property>
        <!-- 指定文件編碼方式,防止出現中文亂碼 -->
        <property name="fileEncoding" value="UTF-8"/>
    </bean>

Java代碼

import com.jf.customer.dto.CustomerInformationDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 * Create By Zany 2018/1/4 0004
 */
public class EmailUtil {

    @Autowired
    private MailSender mailSender;
    @Autowired
    private SimpleMailMessage simpleMailMessage;
    @Value("#{configProperties['mail.head']}")
    private String mailHead;
    @Value("#{configProperties['mail.foot']}")
    private String mailFoot;
    @Value("#{configProperties['mail.subject']}")
    private String mailSubject;

    private Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    public Boolean send(CustomerInformationDto customerInformationDto){

        StringBuffer sb = new StringBuffer();
        sb.append(mailHead + "\n\n");
        sb.append("業務類型:" + customerInformationDto.getBusinessTypeName() + "\n");
        sb.append("用戶類型:" + customerInformationDto.getCustomerTypeName() + "\n");
        sb.append("企業名稱:" + customerInformationDto.getCompanyName() + "\n");
        sb.append("聯繫人 :" + customerInformationDto.getContactName() + "\n");
        sb.append("手機號碼:" + customerInformationDto.getPhoneNumber() + "\n");
        sb.append("郵  箱:" + customerInformationDto.getEmail() + "\n");
        sb.append("QQ 號碼:" + customerInformationDto.getQqNumber() + "\n");
        sb.append("備  注:" + customerInformationDto.getRemarks() + "\n\n\n");
        sb.append(mailFoot);

        simpleMailMessage.setText(sb.toString());

        simpleMailMessage.setSubject(mailSubject);

        try {
            mailSender.send(simpleMailMessage);
            logger.debug("\n[Zany] 郵件發送成功\n");
            return true;
        } catch (MailException e) {
            logger.debug("\n[Zany] 郵件發送失敗 | " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}

以下是異步的代碼片段

private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

        //異步發送郵件,若發送成功,修改郵件發送狀態
        executorService.submit(()->{
            if (emailUtil.send(customerInformationDto)){
                customerInformation.setStatus(1);
                customerInformationMapper.updateStatus(customerInformation);
            }
        });

以上是個人的記錄,也供猿們參考,歡迎提改進意見!

注:個人原創,轉載請註明出處,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章