Java 邮件发送 带附件
2018-03-20 16:22
351 查看
我用的是微软azure发送的
email.properties
pom.xml
MailAuthenticator.java
MailInfo.java
EmailSender.java
PropertiesUtils.java
email.properties
#如果是qq邮箱的话是 smtp.qq.com host=smtp.sendgrid.net #qq邮箱是 465 port=587 userName=azure帐号 #qq邮箱的话是授权码,而不是邮箱密码 password=密码 from=azure帐号 to=收件人帐号
pom.xml
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.2</version> </dependency>
MailAuthenticator.java
import javax.mail.PasswordAuthentication; 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; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }
MailInfo.java
import java.security.GeneralSecurityException; import java.util.Properties; public class MailInfo { private String host;// 邮件服务器域名或IP private String mailPort; private String from;// 发件人 private String to;// 收件人 private String cc;// 抄送人 private String username;// 发件人用户名 private String password;// 发件人密码 private String title;// 邮件的主题 private String content;// 邮件的内容 private String[] attachFileNames;//邮件附件的文件名 /** * 获取邮件参数 * * @return * @throws GeneralSecurityException */ public Properties getProperties() throws GeneralSecurityException { Properties props = new Properties(); props.put("mail.smtp.host", getHost()); props.put("mail.smtp.port", getMailPort()); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); /** 如果用的qq邮箱,下面的注释放开 */ // MailSSLSocketFactory sslSF = new MailSSLSocketFactory(); // sslSF.setTrustAllHosts(true); // props.put("mail.smtp.ssl.enable", "true"); // props.put("mail.smtp.ssl.socketFactory", sslSF); props.put("mail.transport.protocol", "smtp"); props.put("mail.user", getUsername()); props.put("mail.password", getPassword()); return props; } public String getMailPort() { return mailPort; } public void setMailPort(String mailPort) { this.mailPort = mailPort; } public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] attachFileNames) { this.attachFileNames = attachFileNames; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } 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; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
EmailSender.java
import com.example.util.PropertiesUtils; import com.example.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Calendar; import java.util.Properties; public class EmailSender { private static final Logger LOGGER = LoggerFactory.getLogger(EmailSender.class); private static class EmailSenderInstance { private static EmailSender instance = new EmailSender(); } public static EmailSender getInstance() { return EmailSenderInstance.instance; } /** * 以HTML格式发送邮件 * * @param mailInfo 邮件信息 * @return * @throws Exception */ public boolean sendHtmlMail(MailInfo mailInfo) throws Exception { // 需要身份认证,创建一个密码验证器 MailAuthenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword()); Properties prop = mailInfo.getProperties(); // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(prop, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getUsername()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址 to:发送;cc:抄送 Address[][] maillToArr = getMailToAddress(mailInfo); // 设置邮件消息的接收者 if (maillToArr != null && maillToArr[0] != null && maillToArr[0].length > 0) { mailMessage.setRecipients(Message.RecipientType.TO, maillToArr[0]); } if (maillToArr != null && maillToArr[1] != null && maillToArr[1].length > 0) { mailMessage.setRecipients(Message.RecipientType.CC, maillToArr[1]); } // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getTitle()); // 设置邮件消息发送的时间 mailMessage.setSentDate(Calendar.getInstance().getTime()); // MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart multiPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart bodyPart = new MimeBodyPart(); // 设置html邮件消息内容 bodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); multiPart.addBodyPart(bodyPart); // 添加附件 String[] attachFileNames = mailInfo.getAttachFileNames(); if (attachFileNames != null && attachFileNames.length > 0) { for (String attachFile : attachFileNames) { bodyPart = new MimeBodyPart(); // 得到数据源 // DataSource source = new ByteArrayDataSource(is, "application/msexcel"); FileDataSource fds = new FileDataSource(attachFile); // 得到附件本身并放入BodyPart bodyPart.setDataHandler(new DataHandler(fds)); bodyPart.setFileName(MimeUtility.encodeText(fds.getName())); // 得到文件名并编码(防止中文文件名乱码)同样放入BodyPart multiPart.addBodyPart(bodyPart); } } // 设置邮件消息的主要内容 mailMessage.setContent(multiPart); // 发送邮件(qq邮箱) //Transport.send(mailMessage); // 发送邮件(azure) Transport transport = sendMailSession.getTransport(); // Connect the transport object. transport.connect(); // Send the message. transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); // Close the connection. transport.close(); } catch (Exception e) { LOGGER.error("邮件发送失败!", e); return false; } return true; } /** * 创建发送邮件列表地址对象 * * @param mailInfo 邮件信息 * @return Address[0]:发送地址数组;Address[1]:抄送地址数组 */ private Address[][] getMailToAddress(MailInfo mailInfo) { Address[] toAdds = null; Address[] ccAdds = null; try { String to = mailInfo.getTo(); if (StringUtils.isBlank(to)) { throw new NullPointerException("邮件的收件人为空!"); } String[] toMails = to.split(";"); toAdds = new InternetAddress[toMails.length]; for (int index = 0; index < toMails.length; index++) { toAdds[index] = new InternetAddress(toMails[index]); } String cc = mailInfo.getCc(); if (!StringUtils.isBlank(cc)) { String[] ccMails = cc.split(";"); ccAdds = new InternetAddress[ccMails.length]; for (int index = 0; index < ccMails.length; index++) { ccAdds[index] = new InternetAddress(ccMails[index]); } } } catch (Exception e) { LOGGER.error("创建发送邮件列表地址失败!", e); } Address[][] result = {toAdds, ccAdds}; return result; } /** * 构建MailInfo对象 * * @return */ public MailInfo getMailInfo(String title, String content, String[] attachFileNames) { PropertiesUtils instance = PropertiesUtils.getInstance("email.properties"); MailInfo info = new MailInfo(); info.setHost(instance.getValue("host")); info.setMailPort(instance.getValue("port")); info.setUsername(instance.getValue("userName")); info.setPassword(instance.getValue("password")); info.setFrom(instance.getValue("from")); info.setTo(instance.getValue("to")); info.setTitle(title); info.setContent(content); // 添加附件 if (attachFileNames != null) { info.setAttachFileNames(attachFileNames); } return info; } public static void main(String[] args) { EmailSender emailSender = EmailSender.getInstance(); MailInfo mailInfo = emailSender.getMailInfo("Test", "just a test!", new String[]{"G://abc.txt"}); try { boolean success = emailSender.sendHtmlMail(mailInfo); System.out.println(success); } catch (Exception e) { e.printStackTrace(); } } }
PropertiesUtils.java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.Map; import java.util.Properties; public class PropertiesUtils { private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class); private Properties properties; private long latest = 0; private String path; private ClassLoader classLoader; private static Map<String, Properties> proMap; private PropertiesUtils() { classLoader = getClass().getClassLoader(); proMap = MapUtils.newMap(); } public void setPath(String path) { synchronized (this) { this.path = path; } } private void load() { Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = classLoader.getResourceAsStream(path); properties.load(inputStream); setProperties(properties); } catch (IOException e) { logger.error("Load properties failure.", e); } finally { FileUtils.closeIO(inputStream); } } public String getValue(String key) { if (!isLatest()) { load(); } return this.properties.getProperty(key, ""); } private boolean isLatest() { File file = null; try { file = new File(classLoader.getResource(path).toURI()); } catch (URISyntaxException e) { logger.error("File not exists.", e); } long lastModified = file.lastModified(); boolean isLatest = this.latest == lastModified; if (!isLatest) { this.latest = lastModified; } return isLatest; } private void setProperties(Properties properties) { synchronized (this) { this.properties = properties; } } public static PropertiesUtils getInstance(String path) { PropertiesUtils instance = PropertiesUtilsInstance.instance; if (proMap.get(path) == null) { instance.setPath(path); instance.load(); instance.isLatest(); proMap.put(path, instance.properties); } else { instance.setProperties(proMap.get(path)); } return instance; } private static class PropertiesUtilsInstance { private static PropertiesUtils instance = new PropertiesUtils(); } }
相关文章推荐
- [Java Web]stmp发送带附件邮件(附SSL版)
- Java实现邮件发送(附件)
- java发送邮件带附件、格式、可以实现转发、秘密转发等操作
- java发送邮件带附件
- java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html
- 强大的java编程实现邮件发送功能,支持内容,上传多个图片和多个附件
- JAVA邮件发送(文字+图片+附件)【源码】
- Java邮件发送带附件
- Java发送邮件(带附件)
- java发送邮件(多人发送,附件)
- java发送邮件可带附件,以及发送网页等
- java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板
- java邮件发送 实现群发和带附件发送
- Java发送邮件(带附件)
- java发送带附件的邮件/附件图片显示在邮件内容中
- 对象邮件Java Mail 发送附件的邮件
- java 发送邮件+附件
- Java实现发送邮件功能(可带附件)
- Java 邮件email 发送, 邮件内容、邮件附件 名称 乱码处理 完整版
- 在java中 发送邮件 以及定时发送 以及 发送多附件项目下载