java mail发送邮件(单发和群发)
生活随笔
收集整理的這篇文章主要介紹了
java mail发送邮件(单发和群发)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1?服務器郵箱登錄驗證類
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; } }
3?郵件發送器 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 /** * 初始化郵件發送器 * * @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();for( int i = 0 ; i < mailBeanList.size() ; i++ ){MailSendeBean mailBean = mailBeanList.get(i);stringBuffer.append(this.sendToOneUser(mailBean)); }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()); // // 設置郵件內容 // message.setContent(mailSendeBean.getContent().toString(), "text/html;charset=utf-8"); // 向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){result = "["+mailSendeBean.getEmailAddress() +"]未知異常,發送郵件失敗\n " ;}return result;}}
4?郵件發送demo 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 = "imap2.eumail.qq.com"; //郵件服務器String username = "jiangpg@op-moibile.com.cn"; String password = "JianigPeng24212411"; MailSender mailSender = new MailSender(smtpHostName,username,password);return mailSender;}//多個用戶郵件發送private void sendToManyUser() throws Exception{//初始化郵件服務器MailSender mailSender = this.createMailSender();//第一個用戶//創建郵件beanString emailAddress1 = "125429020113@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 = "3313418032173@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(); // 測試多個郵件發送}}
總結
以上是生活随笔為你收集整理的java mail发送邮件(单发和群发)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven项目中测试代码
- 下一篇: 一段java并发编程代码