標籤:使用者 utf-8 tde 專案檔 send reply inter family tco
springboot+maven發送郵件
廢話不多說直接上代碼
1. pom 檔案匯入jar包
<!--郵件發送--> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
2. 郵件方法 我用的是163 郵箱發送
/** * 專案檔根路徑 * @return */ public static String rootPath() { return System.getProperty("user.dir");}}
// 發送郵件 public static Boolean sendEmail() { final Properties props = new Properties(); //登入郵箱伺服器是需要驗證的 props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.163.com"); props.put("mail.smtp.port", 25); //設定協議 props.put("mail.transport.protocol", "smtp"); // 寄件者的帳號 props.put("mail.user", "[email protected]"); // 訪問SMTP服務時需要提供的密碼 非常重要 不是你登陸郵箱的密碼 是需要到163 郵箱設定的SMTP的密碼 props.put("mail.password", "mima"); // 構建授權資訊,用於進行SMTP進行身分識別驗證 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // 使用者名稱、密碼 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用環境屬性和授權資訊,建立郵件會話 Session mailSession = Session.getInstance(props, authenticator);// mailSession.setDebug(true); // 建立郵件訊息 MimeMessage message = new MimeMessage(mailSession); try {String nick = ""; nick = javax.mail.internet.MimeUtility.encodeText("title");// 設定寄件者 InternetAddress from = new InternetAddress(nick + " <"+ props.getProperty("mail.user") + ">"); message.setFrom(from); Address[] a = new Address[1]; // 接收方回複的郵件地址 a[0] = new InternetAddress("[email protected]"); message.setReplyTo(a); // 設定收件者 InternetAddress to = new InternetAddress("[email protected]"); message.setRecipient(MimeMessage.RecipientType.TO, to); // 設定郵件標題 message.setSubject("mailtitle"); //添加附件部分 //郵件內容部分1---常值內容 MimeBodyPart body0 = new MimeBodyPart(); //郵件中的文字部分 body0.setContent("<p>啦啦啦啦</p>","text/html;charset=utf-8"); //郵件內容部分2---附件1 MimeBodyPart body1 = new MimeBodyPart(); //附件1 body1.setDataHandler( new DataHandler( new FileDataSource(UlegalZCUtil.rootPath() + File.separator + "pdf" + File.separator + "templateOL" + ".pdf")) );//./代表項目根目錄下 body1.setFileName( MimeUtility.encodeText("拉拉.pdf") );//中文附件名,解決亂碼 //把上面的3部分組裝在一起,設定到msg中 MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(body0); mm.addBodyPart(body1); message.setContent(mm);// 設定郵件的內容體// message.setContent("題在我使用postman來上傳圖片時候,死活都沒過。。顯示這個,問題在哪呢?", "text/html;charset=UTF-8"); // 發送郵件 Transport.send(message); } catch (Exception e) { String err = e.getMessage(); // 在這裡處理message內容, 格式是固定的 System.out.println("====:"+err); return false; } return true; }
注意 密碼不是郵箱的登陸密碼
java springboot+maven發送郵件