JavaWeb傳送郵件(不包含附件)
阿新 • • 發佈:2019-01-08
使用該功能之前要先開啟郵箱的pop3/smtp功能,具體方法自己去百度。
1.使用的jar包
點選下載
2.後端程式碼
public static void sendCode(String e_mail) {e_mail需要傳送的郵箱地址 Properties pro = new Properties(); pro.setProperty("mail.host","smtp.qq.com");//qq郵箱為smtp.qq.com 163郵箱為smtp.163.com pro.setProperty("mail.transport.protocol","smtp"); pro.setProperty("mail.smtp.auth","true"); Session session = Session.getInstance(pro); // session.setDebug(true);//開啟Debug,可以看到傳送郵件資訊 Transport ts=null; try { ts = session.getTransport(); ts.connect(“smtp.xx.com”,埠號(qq郵箱一般為587,163郵箱為25),“郵箱賬號”,“授權碼”); Message message = creatEmail(session,e_mail); ts.sendMessage(message, message.getAllRecipients());//傳送郵件 } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { SendCodeEmail.setMessage("郵件傳送失敗!"); e.printStackTrace(); }finally { try { if(ts!=null)ts.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private static MimeMessage creatEmail(Session sion,String e_mail) {//建立郵件 MimeMessage message = new MimeMessage(sion); try { message.setFrom(new InternetAddress(從哪裡傳送的地址(
[email protected]))); message.setRecipient(Message.RecipientType.TO, new InternetAddress(e_mail));//傳送到哪裡 message.setSubject(“主題”);//設定主題 message.setContent(“內容”,"text/html;charset=UTF-8");//設定內容 } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } return message; }