使用Spring Mail發送QQ郵件

1、郵箱設置java

須要設置獨立密碼spring

2、配置文件  spring-mail服務器

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop       
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    default-autowire="no" default-lazy-init="false" >

    <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <!-- 主機(QQ的smtp服務器) -->
        <property name="host" value="smtp.qq.com"/>
        <!-- 郵箱名 -->
        <property name="username" value="90XXXX31@qq.com"/>
        <!-- 獨立密碼 -->
        <property name="password" value="123456"/>
        <property name="javaMailProperties">
            <props>
                <!-- 開啓身份認證 -->
                <prop key="mail.smtp.auth">true</prop>
                <!-- 使用默認端口 -->
                <prop key="mail.smtp.starttls.enable">true</prop>
                <!-- 設置超時 -->
                <prop key="mail.smtp.timeout">25000</prop>
            </props>
        </property>
    </bean>
    
</beans>

3、發送類app

package Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Date;

public class SpringJavaMailTest {
    public static void main(String[] args) {
        sendMail();
    }

    public static void sendMail() {
        ApplicationContext application = new ClassPathXmlApplicationContext("spring/spring-*.xml");
        JavaMailSenderImpl sender = (JavaMailSenderImpl) application.getBean("sender");
        sender.setDefaultEncoding("UTF-8");
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setFrom("90XXXX31@qq.com");
            helper.setTo("229XXXX72@qq.com");
            helper.setSentDate(new Date());
            helper.setSubject("郵件主題");
            helper.setText("郵件內容 " + new Date());
            sender.send(message);
            System.out.println("正在發送郵件....");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索