因为工作需要发送邮件。所以上网找了例子,整理了一下发表出来,方便有需要的朋友。
封装邮件信息的一个实体类。
package com.base.myproject.mail; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class MailSenderInfo { public static String TEXT = "text/plain;charset=gb2312"; public static String HTML = "text/html;charset=gb2312"; private String mailServerHost; // 发送邮件的服务器的IP和端口 private String mailServerPort = "25"; private String fromAddress; // 邮件发送者的地址 private String toAddress; // 邮件接收者的地址 private String userName; private String password; // 登陆邮件发送服务器的用户名和密码 private boolean validate = false; // 是否需要身份验证 private String subject; // 邮件主题 private String content; // 邮件的文本内容 private List<Object> attaches = new ArrayList<Object>(); //邮件附件; private String cc; //抄送邮件给某人 private String bc; //隐蔽副本 隐蔽抄送给某人 /** * 获得邮件会话属性 */ 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 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 List<Object> getAttaches() { return attaches; } public void setAttaches(List<Object> attaches) { this.attaches = attaches; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getBc() { return bc; } public void setBc(String bc) { this.bc = bc; } }
邮件用户名密码认证
package com.base.myproject.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyAuthenticator extends Authenticator{ String userName = null; String password = null; public MyAuthenticator(){ } public MyAuthenticator(String username, String password) { this.userName = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(userName, password); } }
发送邮件类
package com.base.myproject.mail; import java.net.URL; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.activation.URLDataSource; import javax.mail.BodyPart; import javax.mail.Message; 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 SendEmail { private BodyPart body; private MailSenderInfo mailInfo; public SendEmail(MailSenderInfo mailInfo){ this.mailInfo = mailInfo; } /* * 设置文件内容的形式 */ public void setBody(String string, String contentType) { try { body = new MimeBodyPart(); DataHandler dh = new DataHandler(string, contentType); body.setDataHandler(dh); } catch (Exception e) { e.printStackTrace(); } } //设置邮件的内容的格式为文本格式 public void setBodyAsText(String string) { setBody(string, MailSenderInfo.TEXT); } //以HTMl的形式存放内容 public void setBodyAsHTML(String string) { setBody(string, MailSenderInfo.HTML); } //从文件中自动导入邮件内容 public void setBodyFromFile(String filename) { try { BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); DataHandler dh = new DataHandler(fds); mdp.setDataHandler(dh); mailInfo.getAttaches().add(mdp); } catch (Exception e) { e.printStackTrace(); } } //从一个URL导入邮件的内容 public void setBodyFromUrl(String url) { try { BodyPart mdp = new MimeBodyPart(); URLDataSource ur = new URLDataSource(new URL(url)); DataHandler dh = new DataHandler(ur); mdp.setDataHandler(dh); mailInfo.getAttaches().add(mdp); } catch (Exception e) { e.printStackTrace(); } } /** * 将String中的内容存放入文件showname,并将这个文件作为附件发送给收件人 * @param string 为邮件的内容 * @param showname 显示的文件的名字 */ public void addAttachFromString(String string, String showname) { try { BodyPart mdp = new MimeBodyPart(); DataHandler dh = new DataHandler(string, MailSenderInfo.TEXT); mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null)); mdp.setDataHandler(dh); mailInfo.getAttaches().add(mdp); } catch (Exception e) { e.printStackTrace(); } } /** * filename为邮件附件 * 在收信人的地方以showname这个文件名来显示 * @param filename * @param showname */ public void addAttachFromFile(String filename, String showname) { try { BodyPart mdp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); DataHandler dh = new DataHandler(fds); mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null)); mdp.setDataHandler(dh); mailInfo.getAttaches().add(mdp); } catch (Exception e) { e.printStackTrace(); } } /** * 将互联网上的一个文件作为附件发送给收信人 * 并在收信人处显示文件的名字为showname * @param url * @param showname */ public void addAttachFromUrl(String url, String showname) { try { BodyPart mdp = new MimeBodyPart(); URLDataSource ur = new URLDataSource(new URL(url)); DataHandler dh = new DataHandler(ur); mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null)); mdp.setDataHandler(dh); mailInfo.getAttaches().add(mdp); } catch (Exception e) { e.printStackTrace(); } } public void send() throws Exception { try { MyAuthenticator authenticator = null; //判断身份是否需要验证 // *****会话类*****// Properties props = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } Session session = Session.getInstance(props,authenticator); // *****消息类*****// MimeMessage msg = new MimeMessage(session); msg.setSubject(mailInfo.getSubject()); // 设置邮件主题 msg.setSentDate(new Date()); // 设置邮件发送时间 // *****地址类*****// if (mailInfo.getFromAddress() != null) msg.addFrom(InternetAddress.parse(mailInfo.getFromAddress())); // 指定发件人 else throw new Exception("没有指定发件人"); if (mailInfo.getToAddress() != null) msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getToAddress()));// 指定收件人 else throw new Exception("没有指定收件人地址"); if (mailInfo.getCc() != null) msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mailInfo.getCc()));// 指定抄送 if (mailInfo.getBc() != null) msg.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailInfo.getBc()));// 指定密送 Multipart mm = new MimeMultipart(); if (body != null) mm.addBodyPart(body);// 设置邮件的附件 if(mailInfo.getAttaches() != null){ for (int i = 0; i < mailInfo.getAttaches().size(); i++) { BodyPart part = (BodyPart) mailInfo.getAttaches().get(i); mm.addBodyPart(part); } } msg.setContent(mm);// 设置邮件的内容 // *****传输类*****// msg.saveChanges();// 保存所有改变 Transport.send(msg); System.out.println("发送成功"); } catch (Exception e) { e.printStackTrace(); throw new Exception("发送邮件失败:", e); } } }
测试类
package com.base.myproject.mail; public class SendEmailTest { /** * @param args */ public static void main(String[] args) { MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.qq.com"); mailInfo.setValidate(true); mailInfo.setUserName("[email protected]"); mailInfo.setPassword("********");// 您的邮箱密码 mailInfo.setFromAddress("[email protected]"); mailInfo.setToAddress("[email protected]"); mailInfo.setSubject("Send Email TEST"); SendEmail sms = new SendEmail(mailInfo); // sms.addAttachFromUrl("http://photo.9haow.cn/2010/12/17/mm_17_01.jpg", "mzba.jpg"); // sms.setBodyFromUrl("http://www.iteye.com/topic/841682#1812080"); sms.setBodyAsHTML("邮件测试啊。"); // sms.addAttachFromFile("D:\\db.pro", "mzba.pro"); try { sms.send(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }