各位程序猿你们好!
Java实现发送邮件功能这技术我相信很多朋友们都会遇到过,尤其是对于做过OA项目的朋友们,一般模块中大部分都会
涉及到发送邮件这个功能,对此我写下自己的心得供大家分享:
我们都知道在客户端和后台交互数据的时候用到了Http协议,那么相应的,邮箱传输也有自己的一套协议,如SMTP,POP3,IMAP。
长话短说,这里我们以163邮箱为例子 首先使用idea创建maven项目,这里需要用到javamail jar包,这里我们使用maven会很方便。
这里我直接在现有项目中使用JUnit Test测试,大家可以新建demo进行练习。
public class MailApplicationTests { //163邮箱的服务器地址 private static final String smtpserver="smtp.163.com"; //端口号 private static final String port="465"; //发送人的邮箱 private static final String account="×××@163.com"; //发送人邮箱的授权码 private static final String pwd="××××"; @Test public void contextLoads() throws UnsupportedEncodingException, MessagingException { //创建邮件配置 Properties properties = new Properties(); //使用的协议 properties.setProperty("mail.transport.protocol","smtp"); //发件人的邮箱的 SMTP 服务器地址 properties.setProperty("mail.smtp.host",smtpserver); properties.setProperty("mail.smtp.port", port); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.smtp.auth", "true"); // 需要请求认证 properties.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl //根据邮件创建会话(传入配置文件) Session session = Session.getDefaultInstance(properties); // 开启debug模式,可以看到更多详细的输入日志 session.setDebug(true); //创建邮件对象传入session MimeMessage email = createEmail(session); Transport transport = session.getTransport(); //获取连接通道,pwd是授权码 transport.connect(smtpserver,account,pwd); //发送 transport.sendMessage(email,email.getAllRecipients()); //关闭session连接 transport.close(); } public MimeMessage createEmail(Session session) throws UnsupportedEncodingException, MessagingException { MimeMessage message = new MimeMessage(session); // address邮件地址, personal邮件昵称, charset编码方式 InternetAddress fromaddress = new InternetAddress(account,"test","utf-8"); //设置邮件的发送方 message.setFrom(fromaddress); InternetAddress acvitaddress = new InternetAddress("×××××@163.com"); //设置邮件接收方 message.setRecipient(Message.RecipientType.TO,acvitaddress); //设置主题 message.setSubject("火锅底料","utf-8"); message.setContent("老子吃火锅你吃火锅底料","text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; } }
小伙伴们记得这里要改下,默认是没有打开的。
好了使用junit测试下就ok了,如果有什么问题可以在下方留言,欢迎大家交流学习。