javaMail邮件发送
生活随笔
收集整理的這篇文章主要介紹了
javaMail邮件发送
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
MailAuthenticator.java
package com.sunrise.jop.common.mail;import javax.mail.Authenticator; import javax.mail.PasswordAuthentication;/** * 服務器郵箱登錄驗證 * */ public class MailAuthenticator extends Authenticator{ private String userName = null;//用于發送郵件的郵箱 private String password = null;//郵箱密碼 public MailAuthenticator() { } public MailAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }MailSendeBean.java
package com.sunrise.jop.common.mail;import java.io.File; import java.util.List; import java.util.Properties;/*** 郵件信息bean* */ public class MailSendeBean {// 郵箱地址private String emailAddress;// 主題private String subject;// 內容private String content;// 附件private List<File> attachFiles;public MailSendeBean() {}public MailSendeBean(String emailAddress, String subject, String content) {this.emailAddress = emailAddress;this.subject = subject;this.content = content;}/*** emailAddress 郵箱地址* subject 主題* content 內容* attachFiles 附件* */public MailSendeBean(String emailAddress, String subject, String content,List<File> attachFiles) {this.emailAddress = emailAddress;this.subject = subject;this.content = content;this.attachFiles = attachFiles;}public String getEmailAddress() {return emailAddress;}public void setEmailAddress(String emailAddress) {this.emailAddress = emailAddress;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public List<File> getAttachFiles() {return attachFiles;}public void setAttachFiles(List<File> attachFiles) {this.attachFiles = attachFiles;}}MailSender.java package com.sunrise.jop.common.mail;import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility;/** * 郵件發送器* */ public class MailSender { //發送郵件的props文件 private final transient Properties props = System.getProperties(); private transient MailAuthenticator authenticator;//郵件服務器登錄驗證 private transient Session session;//郵箱session private final int MAX_SEND_NUMBER = 100;//每次最大發送多少封郵件 private final long SLEEP_TIME = 1000 * 60 * 2; //休息時間private final int REPEAT_TIME = 3 ;// 郵件重發次數/** * 初始化郵件發送器 * * @param smtpHostName * SMTP郵件服務器地址 * @param username * 發送郵件的用戶名(地址) * @param password * 發送郵件的密碼 */ public MailSender(final String smtpHostName, final String username, final String password) { init(username, password, smtpHostName); } /** * 初始化郵件發送器 * * @param username * 發送郵件的用戶名(地址),并以此解析SMTP服務器地址 * @param password * 發送郵件的密碼 */ public MailSender(final String username, final String password) { //通過郵箱地址解析出smtp服務器,適合大多數郵箱 final String smtpHostName = "smtp." + username.split("@")[1]; init(username, password, smtpHostName); } /** * 初始化 * * @param username * 發送郵件的用戶名(地址) * @param password * 密碼 * @param smtpHostName * SMTP主機地址 */ private void init(String username, String password, String smtpHostName) { // 初始化props props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", smtpHostName); // 驗證 authenticator = new MailAuthenticator(username, password); // 創建session session = Session.getInstance(props, authenticator); } /*** 群發郵件* @throws Exception * */public String sendToManyUser( List<MailSendeBean> mailBeanList ) throws Exception{if(mailBeanList==null||mailBeanList.size()==0){return "請設置郵件相關參數\n ";}StringBuffer stringBuffer = new StringBuffer();int count = 0 ;for( int i = 0 ; i < mailBeanList.size() ; i++ ){count ++;MailSendeBean mailBean = mailBeanList.get(i);stringBuffer.append(this.sendToOneUser(mailBean)); if(this.MAX_SEND_NUMBER==count){count = 0 ;Thread.sleep(SLEEP_TIME );}}return stringBuffer.toString();}/*** 單個郵件發送* @throws Exception * */public String sendToOneUser(MailSendeBean mailSendeBean) throws Exception{if(mailSendeBean==null) return "請設置郵件相關參數\n ";//返回提示信息String result = "["+mailSendeBean.getEmailAddress() +"]發送郵件成功\n " ;// 創建mime類型郵件 final MimeMessage message = new MimeMessage(session); // 設置發信人 message.setFrom(new InternetAddress(authenticator.getUserName())); // 設置收件人 message.setRecipient(RecipientType.TO, new InternetAddress(mailSendeBean.getEmailAddress())); // 設置主題 message.setSubject(mailSendeBean.getSubject()); // 設置發送時間 message.setSentDate(new Date()); // 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件Multipart multipart = new MimeMultipart();// 添加郵件正文BodyPart contentPart = new MimeBodyPart();contentPart.setContent(mailSendeBean.getContent().toString(), "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);List<File> attachFiles = mailSendeBean.getAttachFiles();if(attachFiles!=null&&attachFiles.size() >0 ){for( int i = 0 ; i < attachFiles.size() ; i++){File attchFile = attachFiles.get(i);if(attchFile != null){BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(attchFile);attachmentBodyPart.setDataHandler(new DataHandler(source));//MimeUtility.encodeWord可以避免文件名亂碼attachmentBodyPart.setFileName(MimeUtility.encodeWord(attchFile.getName()));multipart.addBodyPart(attachmentBodyPart);}}}// 將multipart對象放到message中message.setContent(multipart);try{Transport.send(message); }catch(Exception e){e.printStackTrace();this.repeatSend(message); //重發}return result;}/*** 郵件發送失敗后,可以重發3次的處理* */private void repeatSend(MimeMessage message){if(message!=null){for( int i = 0 ; i < this.REPEAT_TIME ; i++){try{Transport.send(message);break;}catch(Exception e){e.printStackTrace();}}}}}
MailSenderDemo.java
package com.sunrise.jop.common.mail;import java.io.File; import java.util.ArrayList; import java.util.List;/*** 郵件發送demo* */ public class MailSenderDemo {//創建郵件服務器private MailSender createMailSender(){String smtpHostName = "imap.exmail.qq.com"; //郵件服務器String username = "jiangp@op-mobile.com.cn"; String password = "JiangPeng341341"; MailSender mailSender = new MailSender(smtpHostName,username,password);return mailSender;}//多個用戶郵件發送private void sendToManyUser() throws Exception{//初始化郵件服務器MailSender mailSender = this.createMailSender();//第一個用戶//創建郵件beanString emailAddress1 = "12542902013@qq.com"; String subject1 = "郵件主題測試1"; String content1 = "郵件內容測試1"; //附件File txtFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");File docFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");File excelFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testExcel.xls");File photoFile1 = new File("D:"+File.separator+ "emailTest" + File.separator + "testPhoto.jpg");List<File> attchFiles1 = new ArrayList<File>();attchFiles1.add(txtFile1); attchFiles1.add(docFile1);attchFiles1.add(excelFile1); attchFiles1.add(photoFile1);//封裝單個郵件beanMailSendeBean mailSendeBean1 = new MailSendeBean( emailAddress1, subject1, content1,attchFiles1);//第二個用戶String emailAddress2 = "33134180173@qq.com"; String subject2 = "郵件主題測試2"; String content2 = "郵件內容測試2"; //附件File txtFile2 = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");File docFile2 = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");List<File> attchFiles2 = new ArrayList<File>();attchFiles2.add(txtFile2); attchFiles2.add(docFile2);//封裝單個郵件beanMailSendeBean mailSendeBean2 = new MailSendeBean( emailAddress2, subject2, content2,attchFiles2);//封裝多個郵件beanList<MailSendeBean> mailList = new ArrayList<MailSendeBean>();mailList.add(mailSendeBean1); mailList.add(mailSendeBean2);// 發送郵件String resultMessage = mailSender.sendToManyUser(mailList);System.out.println("resultMessage = " + resultMessage);} //單個郵件發送private void sendToOneUser() throws Exception{//初始化郵件服務器MailSender mailSender = this.createMailSender();//創建郵件beanString emailAddress = "1254290201@qq.com"; String subject = "郵件主題測試"; String content = "郵件內容測試"; //附件File txtFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testText.txt");File docFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testDoc.doc");File excelFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testExcel.xls");File photoFile = new File("D:"+File.separator+ "emailTest" + File.separator + "testPhoto.jpg");List<File> attchFiles = new ArrayList<File>();attchFiles.add(txtFile); attchFiles.add(docFile);attchFiles.add(excelFile); attchFiles.add(photoFile);//封裝郵件beanMailSendeBean mailSendeBean = new MailSendeBean( emailAddress, subject, content,attchFiles);// 發送郵件String resultMessage = mailSender.sendToOneUser(mailSendeBean);System.out.println("resultMessage = " + resultMessage);}public static void main(String args[]) throws Exception{MailSenderDemo mailDemo = new MailSenderDemo();mailDemo.sendToOneUser(); // 測試單個郵件發送 // mailDemo.sendToManyUser(); // 測試多個郵件發送}}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的javaMail邮件发送的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xstream解析xml字符串和生成对象
- 下一篇: 一 冒泡排序