java郵件開發之javax.mail開發


使用javax.mail實現郵件的發送(使用qq郵箱發送)

  1、引入javax.mail依賴

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

2、在application.properties文件中配置

mail.config.SMTP_host=smtp.qq.com
mail.config.SMTP_port=25   #端口號,一般有ssl的時候端口號是其他的
mail.config.SMTP_auth=true  #連接校驗
mail.config.STMP_user=xxxx@qq.com  #發件人用戶
mail.config.STMP_pass=xxxxx #授權碼
mail.config.SMTP_from=2428202862@qq.com  #發件人
mail.config.SMTP_fromnick=xxx對方郵箱顯示的不是qq號而是nickname

3、配置類bean

package lut.mail;
public class MailConfig {
     private String SMTP_host;
     private  int SMTP_port;
     private boolean SMTP_auth;
     private String STMP_user;
     private String STMP_pass;
     private String SMTP_from;
     private String SMTP_fromnick;
 getter/setter......
}

4、配置類注入

package lut.mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MailConfiguration {
    @Value("${mail.config.SMTP_host}")
    private String SMTP_host;
    @Value("${mail.config.SMTP_port}")
    private  int SMTP_port;
    @Value("${mail.config.SMTP_auth}")
    private boolean SMTP_auth;
    @Value("${mail.config.STMP_user}")
    private String STMP_user;
    @Value("${mail.config.STMP_pass}")
    private String STMP_pass;
    @Value("${mail.config.SMTP_from}")
    private String SMTP_from;
    @Value("${mail.config.SMTP_fromnick}")
    private String SMTP_fromnick;
    @Bean
    public MailConfig getmailConfig(){
        MailConfig mc = new MailConfig();
         mc.setSMTP_host(SMTP_host);
         mc.setSMTP_port(SMTP_port);
         mc.setSMTP_auth(SMTP_auth);
         mc.setSTMP_user(STMP_user);
         mc.setSTMP_pass(STMP_pass);
         mc.setSMTP_from(SMTP_from);
         mc.setSMTP_fromnick(SMTP_fromnick);
        return mc;
    }
}

5、實現Authenticator抽象類(此類做session實例化是會用到)

package lut.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailSMTPAuthenticator extends Authenticator{
   private String sName;
   private String sPassword;
   public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(sName, sPassword);
    } 
public String getsName() {
    return sName;
}
public void setsName(String sName) {
    this.sName = sName;
}
public String getsPassword() {
    return sPassword;
}
public void setsPassword(String sPassword) {
    this.sPassword = sPassword;
}     
}

6、mail郵件發送實現

package lut.mail;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
@SuppressWarnings("unused")
public class MailService {


@Autowired
private MailConfig mailconfig;
public void senMail(){
    System.out.println(mailconfig.toString());
    MimeMessage mMessage = null;
    Session mailSession = null;
    //1、連接郵件服務器的參數配置附件名稱過長亂碼解決,關鍵詞false
    System.setProperty("mail.mime.splitlongparameters","false");
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", mailconfig.getSMTP_host());
    props.setProperty("mail.smtp.port", mailconfig.getSMTP_port()+"");
    props.setProperty("mail.smtp.auth", mailconfig.getSMTP_auth()+"");
    // 設置SMTP連接和發送郵件的超時時間,因為缺省是無限超時,單位毫秒
    props.setProperty("mail.smtp.connectiontimeout", "15000");//SMTP服務器連接超時時間
    props.setProperty("mail.smtp.timeout","60000");//發送郵件超時時間
    if(mailconfig.getSMTP_auth()){
        MailSMTPAuthenticator smtpAutr= new MailSMTPAuthenticator();
                smtpAutr.setsName(mailconfig.getSTMP_user());
                smtpAutr.setsPassword("sunwei951025");
       mailSession = Session.getInstance(props, smtpAutr); 
    }else{
           mailSession = Session.getInstance(props); 
    }
    
    mailSession.setDebug(true);
    mMessage = new MimeMessage(mailSession);
    try {
         //發件人
        InternetAddress formAddress = new InternetAddress(mailconfig.getSMTP_from());
        formAddress.setPersonal("了然於心");
        mMessage.setFrom(formAddress);
        //發送時間
        mMessage.setSentDate(new Date());
        //收件人
         InternetAddress[] toAddress =  {new InternetAddress("sunw@hrocloud.com"),new InternetAddress("sunwei1995sh@126.com")};
         mMessage.setRecipients(Message.RecipientType.TO,toAddress);
         //主題
         mMessage.setSubject("孫維主題");

        //內容
         MimeBodyPart contentBodyPart = new MimeBodyPart();
        contentBodyPart.setContent("此郵件為系統自己主動發送<img src='cid:a'><img src='cid:a'>","text/html;charset=UTF-8"); //cid必須和相關圖片的ContentID相同才會在郵件正文顯示圖片。
//圖片 
MimeBodyPart imgAff = new MimeBodyPart();
imgAff.setDataHandler(
new DataHandler(new FileDataSource("d:\\IO.jpg")));
imgAff.setContentID(
"a");
MimeMultipart addM
= new MimeMultipart();
addM.addBodyPart(contentBodyPart);
addM.addBodyPart(imgAff);
addM.setSubType(
"related");
// 圖班與正文的 body
MimeBodyPart affContent = new MimeBodyPart();
affContent.setContent(addM);
//附件
MimeBodyPart affDoc
= new MimeBodyPart();
affDoc.setDataHandler(
new DataHandler(new FileDataSource("d:\\業務流程腳本.sql")));
affDoc.setFileName(MimeUtility.encodeText(
"業務流程腳本.sql"));
affDoc.setContentID(
"UUud");
MimeMultipart text
= new MimeMultipart();
text.addBodyPart(affContent);
text.addBodyPart(affDoc);
text.setSubType(
"mixed");
mMessage.setContent(text);
mMessage.saveChanges();
Transport transport
= null;
transport
= mailSession.getTransport("smtp");
transport.connect(mailconfig.getSTMP_user(),mailconfig.getSTMP_pass());
transport.sendMessage(mMessage, mMessage.getAllRecipients());
transport.close();
}
catch (
MessagingException | UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

 帶圖片的郵件概念圖

圖片截至:https://www.cnblogs.com/lls1413/p/javamail.html


免責聲明!

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



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