前台頁面展示
協定類型:smtp;郵件伺服器主機:smtp.163.com;端口号:465;我們使用的是阿裡雲釋出的系統,這裡注意端口号不能使用之前的80端口;而是使用465端口。使用者名,密碼填寫自己注冊的郵箱的賬号密碼:注意這裡的郵箱必須把smtp服務開啟,具體如何開啟,可以百度一下。發送人郵箱和之前郵箱賬号一緻,名稱則是目前名稱。
具體發送的流程
我們已經把我們的服務郵箱存入到資料庫之中,下面則是需要開始我們的郵件發送的過程了:
public static void sendEmail(Email data, String toEmail, String name, String path, String packagename) throws MessagingException, UnsupportedEncodingException {
String EMAILTITLE = name + packagename + "報告";
String EMAILCONTENT = "尊敬的客戶您好: "+"\n"
+ " 您好,您的報告已經生成,請下載下傳附件檢視您的報告。"+"\n"
+" (此郵件由系統自動發送,請勿回複)"+"\n"+"\n"+" ,祝您健康、平安!";
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = new Properties();
props.setProperty("mail.smtp.host", data.getServerHost());
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", data.getServerPort().toString());
props.setProperty("mail.smtp.socketFactory.port", data.getServerPort().toString());
props.setProperty("mail.smtp.timeout", "80000");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(data.getUsername(), data.getPassword());
}});
Message msg = new MimeMessage(session);
// 設定發件人和收件人
msg.setFrom(new InternetAddress(data.getUsername()));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject(EMAILTITLE); // 标題
msg.setText(EMAILCONTENT);// 内容
// 向multipart對象中添加郵件的各個部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 設定郵件的文本内容
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(EMAILCONTENT);
multipart.addBodyPart(contentPart);
// 添加附件
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(path);
messageBodyPart1.setDataHandler(new DataHandler(fdatasource));
messageBodyPart1.setFileName(fdatasource.getName());
multipart.addBodyPart(messageBodyPart1);
msg.setContent(multipart);
msg.setSentDate(new Date());
Transport.send(msg);
}
調用這個代碼 ,就可以将需要發送的内容,發送客戶了。