JAVA實現郵件發送功能(賬號注冊驗證碼、賬號激活等)


第一步,導入JAR包,JAR包下載地址[http://pan.baidu.com/s/1kVRvGyF]

如果是Maven,請直接在Pom文件中加入

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>

如果是SpringBoot,請直接在Pom文件中加入

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

正式代碼:

  首先書寫一個工具類:

  MailUtil

  

 1 import javax.mail.*;
 2 import javax.mail.internet.InternetAddress;
 3 import javax.mail.internet.MimeMessage;
 4 import java.util.Properties;
 5 
 6 /**
 7  * 郵件工具類
 8  */
 9 public class MailUtil {
10     /**
11      * 發送郵件
12      * @param to 給誰發
13      * @param text 發送內容
14      */
15     public static void send_mail(String to,String text) throws MessagingException {
16         //創建連接對象 連接到郵件服務器
17         Properties properties = new Properties();
18         //設置發送郵件的基本參數
19         //發送郵件服務器(注意,此處根據你的服務器來決定,如果使用的是QQ服務器,請填寫smtp.qq.com)
20         properties.put("mail.smtp.host", "smtp.huic188.com");
21         //發送端口(根據實際情況填寫,一般均為25
22         properties.put("mail.smtp.port", "25");
23         properties.put("mail.smtp.auth", "true");
24         //設置發送郵件的賬號和密碼
25         Session session = Session.getInstance(properties, new Authenticator() {
26             @Override
27             protected PasswordAuthentication getPasswordAuthentication() {
28                 //兩個參數分別是發送郵件的賬戶和密碼(注意,如果配置后不生效,請檢測是否開啟了 POP3/SMTP 服務,QQ郵箱對應設置位置在: [設置-賬戶-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務])
29                 return new PasswordAuthentication("admin@huic188.com","這里寫你的賬號的密碼");
30             }
31         });
32 
33         //創建郵件對象
34         Message message = new MimeMessage(session);
35         //設置發件人
36         message.setFrom(new InternetAddress("admin@huic188.com"));
37         //設置收件人
38         message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
39         //設置主題
40         message.setSubject("這是一份測試郵件");
41         //設置郵件正文  第二個參數是郵件發送的類型
42         message.setContent(text,"text/html;charset=UTF-8");
43         //發送一封郵件
44         Transport.send(message);
45     }
46 }

  測試類:

  TEST:

  

import javax.mail.MessagingException;

/**
 * 測試類
 */
public class Test {
    public static void main(String[] args) {
        try {
       // 請將此處的 690717394@qq.com 替換為您的收件郵箱號碼 MailUtil.send_mail(
"690717394@qq.com", String.valueOf(Math.random() * 999)); System.out.println("郵件發送成功!"); } catch (MessagingException e) { e.printStackTrace(); } } }
測試結果: 正常發送!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM