发布时间:2018-03-17作者:laosun阅读(1901)
今天刚写了一个java发送email的功能,分享一下吧! 简单的不得了。使用的是com.sun.mail » javax.mail
后台发送电子邮件还是很常见的,比如用户注册、密码找回、以及一些系统性通知等等,所以作为一名java程序员,还是有必要学会这项技能的。
这个功能非常的简单,直接上源码吧,里边都有注释。
import java.util.Date; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; 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 org.apache.commons.lang.StringUtils; import com.sunjs.model.TBlogEmailLog; import com.sunjs.model.TMessageTemplate; import com.sunjs.utils.Const; import com.sunjs.utils.DateUtils; import com.sunjs.utils.EncryptionKit; /** * 邮件发送类 * @author sun */ public class SendEmail { public static final String HOST = "smtp.mxhichina.com"; public static final String PROTOCOL = "smtp"; public static final int PORT = 25; public static final String FROM = "你的发件账号";// 发件人的email public static final String PWD = "你的发件密码";// 发件人密码 /** * 获取Session * * @return */ private static Session getSession() { Properties props = new Properties(); /** 设置发送邮件的邮件服务器的属性(这里使用QQ的smtp服务器) **/ props.put("mail.smtp.host", HOST);// 设置服务器地址 props.put("mail.store.protocol", PROTOCOL);// 设置协议 props.put("mail.smtp.port", PORT);// 设置端口 props.put("mail.smtp.auth", true);// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条) Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(FROM, PWD); } }; /** 用刚刚设置好的props对象构建一个session **/ // Session session = Session.getDefaultInstance(props, authenticator); Session session = Session.getInstance(props, authenticator); /** 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使用(你可以在控制台(console)上看到发送邮件的过程) **/ session.setDebug(false); return session; } /** * 异步发送email * @author sun * @param toEmail * @param type * @return */ public static boolean asynchronizedSendEmail(final String toEmail, final String subject, final String content) { Boolean flag = Boolean.FALSE; FutureTask<Boolean> futureTask = null; ExecutorService excutorService = Executors.newCachedThreadPool(); // 执行任务 futureTask = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return sendEmail(toEmail, subject, content); } }); excutorService.submit(futureTask); try { // 任务没超时说明发送成功 flag = futureTask.get(5L, TimeUnit.SECONDS); } catch (InterruptedException e) { futureTask.cancel(true); e.printStackTrace(); } catch (ExecutionException e) { futureTask.cancel(true); e.printStackTrace(); } catch (TimeoutException e) { futureTask.cancel(true); e.printStackTrace(); } finally { excutorService.shutdown(); } return flag; } private static boolean sendEmail(String toEmail, String subject, String content) { boolean result = false; if (StringUtils.isNotEmpty(toEmail) && StringUtils.isNotEmpty(subject) && StringUtils.isNotEmpty(content)) { Session session = getSession(); // 用session为参数定义消息对象 MimeMessage message = new MimeMessage(session); try { // 加载发件人地址 message.setFrom(new InternetAddress(FROM)); if (toEmail.indexOf(",") != -1) { String[] users = toEmail.split(","); // 群发 InternetAddress[] address = new InternetAddress[users.length]; for (int i = 0; i < users.length; i++) { address[i] = new InternetAddress(users[i]); } // 加载收件人地址 message.addRecipients(Message.RecipientType.TO, address); } else { // 单个发 message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); } // 加载标题 message.setSubject(subject); // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // 设置邮件的文本内容 BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(content, "text/html; charset=utf-8"); multipart.addBodyPart(contentPart); // 将multipart对象放到message中 message.setContent(multipart); // 保存邮件 message.saveChanges(); // 发送邮件 Transport transport = session.getTransport("smtp"); // 连接服务器的邮箱 transport.connect(HOST, FROM, PWD); // 把邮件发送出去 transport.sendMessage(message, message.getAllRecipients()); transport.close(); result = true; } catch (Exception e) { e.printStackTrace(); } } return result; } }
maven :
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.1</version> </dependency>
到此为止,看不明白,运行不通的,自己去搜,我拯救不了你!!!
版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/53688c1fb0044cfd95da5785432152fd.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。