java mail邮件发送(带附件)有三个类
MailSenderInfo.java
package mail; import java.util.Properties; import java.util.Vector; public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private String mailServerPort = "25"; // 邮件发送者的地址 private String fromAddress; // 邮件接收者的地址 private String toAddress; // 登陆邮件发送服务器的用户名和密码 private String userName; private String password; // 是否需要身份验证 private boolean validate = false; // 是否启用ssl private boolean validateSSL = false; // 邮件主题 private String subject; // 邮件的文本内容 private String content; // 邮件附件的文件名 private Vector attachFileNames; /** * 获得邮件会话属性 */ public Properties getProperties(){ Properties p = new Properties(); p.put("mail.smtp.host", this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost) { this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort; } public boolean isValidate() { return validate; } public void setValidate(boolean validate) { this.validate = validate; } public Vector getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(Vector attachFileNames) { this.attachFileNames = attachFileNames; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String textContent) { this.content = textContent; } public boolean isValidateSSL() { return validateSSL; } public void setValidateSSL(boolean validateSSL) { this.validateSSL = validateSSL; } }
MailAuthenticator.java
package mail; import javax.mail.*; public class MailAuthenticator extends Authenticator { private String userName; private String password; public MailAuthenticator() { } public MailAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }
SimpleMailSender.java
package mail; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * 简单邮件(带附件的邮件)发送器 */ public class SimpleMailSender { /** * 以文本格式发送邮件 * * @param mailInfo * 待发送的邮件的信息 */ public boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session .getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以HTML格式发送邮件 * * @param mailInfo * 待发送的邮件信息 */ public static boolean sendHtmlMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); // 如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session .getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } /** * 以html发送邮件(带附件) * * @param mailInfo * 待发送的邮件的信息 */ public boolean sendHtmlAndAffixMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if(mailInfo.isValidateSSL()){ pro.put("mail.smtp.starttls.enable","true"); pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } // 如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session session = Session.getDefaultInstance(pro, authenticator); try { MimeMessage msg = new MimeMessage(session); // 构造MimeMessage 并设定基本的值 // MimeMessage msg = new MimeMessage(); msg.setFrom(new InternetAddress(mailInfo.getFromAddress())); // msg.addRecipients(Message.RecipientType.TO, address); // //这个只能是给一个人发送email msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getToAddress())); msg.setSubject(MimeUtility.encodeText(mailInfo.getSubject())); Multipart mp = new MimeMultipart();// 构造Multipart MimeBodyPart mbpContent = new MimeBodyPart();// 向Multipart添加正文 mbpContent.setContent(mailInfo.getContent(), "text/html;charset=GB2312"); mp.addBodyPart(mbpContent);// 向MimeMessage添加(Multipart代表正文) Vector file = mailInfo.getAttachFileNames(); Enumeration efile = file.elements();// 向Multipart添加附件 while (efile.hasMoreElements()) { MimeBodyPart mbpFile = new MimeBodyPart(); String filename = efile.nextElement().toString(); System.out.println(filename.toLowerCase()); FileDataSource fds = new FileDataSource(filename); mbpFile.setDataHandler(new DataHandler(fds)); System.out.println(fds.getName()); mbpFile.setFileName(MimeUtility.encodeText(fds.getName())); // 向MimeMessage添加(Multipart代表附件) mp.addBodyPart(mbpFile); } file.removeAllElements(); // 向Multipart添加MimeMessage msg.setContent(mp); msg.setSentDate(new Date()); msg.saveChanges(); // 发送邮件 Transport transport = session.getTransport("smtp"); transport.connect(mailInfo.getMailServerHost(), mailInfo .getUserName(), mailInfo.getPassword()); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception mex) { mex.printStackTrace(); return false; } return true; } }
测试类
package mail; import java.util.Vector; public class MailTest { /** * @param args */ public static void main(String[] args) { //这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.XXXXXX.com"); mailInfo.setMailServerPort("465"); mailInfo.setValidate(true); mailInfo.setValidateSSL(true); mailInfo.setUserName("[email protected]<span style="font-family: Arial, Helvetica, sans-serif;">XXXXXX</span><span style="font-family: Arial, Helvetica, sans-serif;">.com"); </span> mailInfo.setPassword(pwd);//您的邮箱密码 mailInfo.setFromAddress(<span style="font-family: Arial, Helvetica, sans-serif;">"[email protected]</span><span style="font-family: Arial, Helvetica, sans-serif;">XXXXXX</span><span style="font-family: Arial, Helvetica, sans-serif;">.com"</span><span style="font-family: Arial, Helvetica, sans-serif;">); </span> mailInfo.setToAddress("[email protected]"); mailInfo.setSubject("设置邮箱标题"); mailInfo.setContent("今天应该是魅族粉的狂欢日!"+ "今天魅族在北京正式发布MX4,魅族MX4采用5.36寸1920×1152分辨率屏幕(PPI418),搭载联发科八核处理器,提供2070万像素摄像头,配备3100mAh电池,运行全新的Flyme 4.0系统,支持移动与联通网络双4G,安兔兔跑分46124分,提供深灰色、纯白色及土豪金版本,16G版售价1799元,32G版售价1999元。"); //这个类主要来发送邮件 Vector fileNames = new Vector(); fileNames.add("D:\\delete\\周报表20140903103213.xls"); fileNames.add("D:\\delete\\复件 周报表20140903103213.xls"); fileNames.add("D:\\delete\\复件 (2) 周报表20140903103213.xls"); mailInfo.setAttachFileNames(fileNames); SimpleMailSender sms = new SimpleMailSender(); // sms.sendTextMail(mailInfo);//发送文体格式 sms.sendHtmlAndAffixMail(mailInfo);//发送html格式 } }
时间: 2024-09-30 04:52:52