Java程式設計師從笨鳥到菜鳥(五十七) java 實現郵箱驗證
阿新 • • 發佈:2018-12-14
1、郵箱開啟服務
以 QQ 郵箱為例: 進入網頁郵箱 -> 設定
開啟之後會得到一個授權碼,待會配置需要這個授權碼
2、新增依賴
在 pom.xml 新增依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> // 版本號根據自己使用的 spring 版本號對應 </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>${commons-httpclient.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency>
3、配置檔案
application.properties
:
# QQ 郵箱配置 使用 465 埠會出現超時錯誤,使用 587 親測無異常 qq.mail.host = smtp.qq.com qq.mail.port = 587 qq.mail.username = ******* # 傳送人郵箱 qq.mail.password = *********** # 授權碼 qq.mail.default-encoding = UTF-8 # 163 郵箱配置 163.mail.host = smtp.163.com # 126 郵箱配置 126.mail.host = smtp.126.com
applicationContext.xml
:
<!-- 載入 application.properties 配置檔案 --> <context:property-placeholder location="classpath:application.properties"/> <!-- 郵件傳送 --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${qq.mail.host}"/> <property name="port" value="${qq.mail.port}"/> <property name="username" value="${qq.mail.username}"/> <property name="password" value="${qq.mail.password}"/> <property name="defaultEncoding" value="${qq.mail.default-encoding}"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.a uth">true</prop> <prop key="mail.smtp.timeout">25000</prop> <!--<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>--> <!-- 如果是網易郵箱, mail.smtp.starttls.enable 設定為 false--> <prop key="mail.smtp.starttls.enable">true</prop> </props> </property> </bean>
4、業務邏輯層
MailService.java
介面
package service;
/**
* create by [email protected] on 2018/10/8 14:30
* 傳送郵件業務介面
**/
public interface MailService {
/**
* 簡單文字郵件傳送
* @param to 郵件接收者
* @param subject 郵件主題
* @param content 郵件內容
* */
void sendSimpleMail(String to, String subject, String content);
/**
* 傳送富文字郵件 支援文字、附件、HTML、圖片等
* @param to 郵件接收者
* @param subject 郵件主題
* @param content 郵件內容
* */
void sendHtmlMail(String to, String subject, String content);
/**
* 傳送帶附件的郵件
* @param to 郵件接收者
* @param subject 郵件主題
* @param content 郵件內容
* @param filePath 附件地址
* */
void sendAttatchmentMail(String to, String subject, String content, String filePath);
}
實現:
MailServiceImpl.java
package service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
/**
* create by [email protected] on 2018/10/8 14:33
* 郵件傳送業務邏輯層實現
**/
@Service("MailService")
public class MailServiceImpl implements MailService{
@Autowired
private JavaMailSender mailSender;
@Value("${qq.mail.username}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(content);
try {
mailSender.send(simpleMailMessage);
System.out.println("普通文字郵件已傳送");
} catch (Exception e) {
System.out.println("普通文字郵件傳送異常");
e.printStackTrace();
}
}
@Override
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8"); // 設定字元編碼,避免中文亂碼
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(mimeMessage);
System.out.println("HTML 格式郵件傳送成功");
} catch(MessagingException e) {
System.out.println("HTML 格式郵件傳送異常");
e.printStackTrace();
}
}
@Override
public void sendAttatchmentMail(String to, String subject, String content, String filePath) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // 設定字元編碼,避免中文亂碼
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName,file);
mailSender.send(mimeMessage);
System.out.println("帶附件郵件傳送成功");
} catch(MessagingException e) {
System.out.println("帶附件郵件傳送異常");
e.printStackTrace();
}
}
}
5、測試類:
MailTest.java
:
package test;
import org.junit.Test;
import service.MailService;
import javax.annotation.Resource;
/**
* create by [email protected] on 2018/10/8 15:01
* 郵件傳送測試類
**/
public class MailTest extends BaseJunit{
@Resource(name="MailService")
private MailService mailService;
@Test
public void mailSendTest() throws Exception {
mailService.sendSimpleMail("[email protected]", "郵件收發測試", "這是第一封郵件");
System.out.println("郵件傳送成功");
}
@Test
public void mailHtmlTest() throws Exception {
String content = "<html>\n" + "<body>\n" +
"<h3>hello world 這是第一封 html 郵件!</h3>\n" + "<a href=https://www.baidu.com>啟用</a>\n" +
"</body>\n" + "</html>\n";
mailService.sendHtmlMail("[email protected]", "郵件收發測試", content);
System.out.println("HTML 格式郵件傳送成功");
}
@Test
public void mailAttatchmentTest() throws Exception {
String filePath = "**********"; // 加入附件路徑
mailService.sendAttatchmentMail("[email protected]", "郵件收發測試", "有附件,請查收", filePath);
System.out.println("帶附件郵件傳送成功");
}
}
6、測試結果: