JAVA實現郵箱推送工具(支援群發)
阿新 • • 發佈:2020-11-23
-
需要引用的jar包;
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
-
工具類;
`package cn.qin.xxltest.xxltask.service;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Email {
private static final String MAIL_USER = "******@qq.com"; //郵件伺服器登入使用者名稱 private static final String MAIL_PASSWORD = "bybtfpssyfvahrbeid"; //郵件伺服器登入密碼 private static final String MAIL_FROM_SMTP = "[email protected]"; //傳送郵件地址 public void sendmail(String[] mailArray,String subject,String content){ Properties props = new Properties(); //設定伺服器驗證 props.setProperty("mail.smtp.auth", "true"); //設定傳輸協議 props.setProperty("mail.transport.protocol", "smtp"); //選擇服務型別 props.setProperty("mail.host", "smtp.qq.com"); //通過認證建立一個session例項 Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(MAIL_USER,MAIL_PASSWORD); } } ); //顯示郵件傳送過程中的互動資訊 session.setDebug(true); Message msg = new MimeMessage(session); Transport transport=null; try { //郵件傳送人 msg.setFrom(new InternetAddress(MAIL_FROM_SMTP)); //郵件主題 msg.setSubject(subject); //郵件內容 msg.setText(content); int len=mailArray.length; InternetAddress address[]=new InternetAddress[len]; for (int i = 0; i < mailArray.length; i++) { address[i]=new InternetAddress(mailArray[i]); } //郵件接收方 msg.addRecipients(Message.RecipientType.TO, address); transport.send(msg); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(transport!=null){ transport.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws Exception{ Email demo2=new Email(); String[] mailArray ={"******@qq.com","******@eautosh.com"}; String subject="冬天來啦!"; String content="Hello world啊!"; demo2.sendmail(mailArray,subject,content); }
}`
3.qq郵件伺服器登入密碼獲取方式;
第一步:登入郵箱,點選設定;
第二步:選擇賬戶;
第三步:開啟POP3/SMTP服務,獲取密碼