1.使用Spring发送带附件的电子邮件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="192.168.8.71"></property><!-- 服务器 --> <property name="port" value="25"></property><!-- 端口 --> <property name="username" value="wxk"></property><!-- 用户名 --> <property name="password" value="wxk"></property><!-- 密码 --> <property name="protocol" value="smtp" ></property><!-- 协议 --> <property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 --> <property name="javaMailProperties"> <props> <!-- 设置SMTP服务器需要用户验证 --> <prop key="mail.smtp.auth">true</prop> </props> </property> </bean> <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment"> <property name="mailSender" ref="mailSender"></property> </bean> </beans>
log4j.rootLogger=info,console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n
package cn.bdqn; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); try{ MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment"); mailWithAttach.send(); }catch(Exception e){ System.out.print(e.toString()); } } }
package cn.bdqn; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; public class MailWithAttachment { private JavaMailSender mailSender; //必须使用 JavaMailSender public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void send() throws MessagingException,IOException{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom("wxk@mail.com"); helper.setTo("wj@mail.com"); helper.setSubject("等待是种执着"); helper.setText("青鸟的岁月似流年,又有多少青春如风逝去,不要让这座城市只留下无尽的回忆,却没有留下我们一起走过的青春," + "青春不是生命的一瞬,而是一种自然的心境!"); //添加附件1 ClassPathResource file1 = new ClassPathResource("/cn/bdqn/attachfiles/QQ图片20161214191111.jpg"); helper.addAttachment(file1.getFilename(), file1.getFile()); //添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题 ClassPathResource file2 = new ClassPathResource("/cn/bdqn/attachfiles/附件测试文件.doc"); helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile()); mailSender.send(mimeMessage); } }
上传邮件成功
2.使用Spring发送简单邮件
大配置和log4j还要架包同上省略
package cn.bdqn; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; public class Mail { private MailSender mailSender; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void send(){ SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("wxk@mail.com"); message.setTo("wj@mail.com"); message.setSubject("会议通知fsb发布"); message.setText("jerry你好!请于明天下午16:00 准时到B01会议室召开技术讨论会。"); mailSender.send(message); } }
package cn.bdqn; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /*测试简单邮件*/ Mail mail = (Mail)context.getBean("mail"); mail.send(); } }
3.使用Spring邮件服务和FreeMarker模板技术发送邮件
大配置和log4j还要架包同上省略
package cn.bdqn.pojo; public class Mail { private String to; private String subject; private String content; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package cn.bdqn.service; import cn.bdqn.pojo.Mail; public class LeaveService { private MailService mailService; public void setMailService(MailService mailService) { this.mailService = mailService; } public void updateLeave(){ //省略审批请假申请 //查询数据库获取相关信息 String approver = "张来"; Mail mail = new Mail(); mail.setTo("wj@mail.com"); mail.setSubject("请假流程确认邮件"); StringBuffer sb = new StringBuffer(); sb.append("<html><head>"); sb.append("<meta http-equiv="content-type" content="text/html;charset=utf-8">"); sb.append("<head><body>"); sb.append("<font color='blue' size='4' face='Arial'>"); sb.append("OA系统温馨提示:</font><br/><br/>"); sb.append(" "); sb.append("在OA系统中,您提交的“请假流程” "+ approver +" 已经审批完成,点击如下链接可登陆系统查看流程,谢谢。" + "如果登录时忘记密码,可以在网站登录页找回。<br/>"); sb.append("<br/><br/> <a href='http://www.jboa.com'>http://www.jboa.com</a>"); sb.append("<br/><br/> -----本邮件为系统自动发出,请勿回复-----"); mail.setContent(sb.toString()); try{ mailService.send(mail); }catch(Exception e){ e.printStackTrace(); } } }
package cn.bdqn.service; import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import cn.bdqn.pojo.Mail; public class MailService { private JavaMailSender mailSender; //必须使用 JavaMailSender public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public void send(Mail mail) throws MessagingException,IOException{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); helper.setFrom("wxk@mail.com"); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); helper.setText(mail.getContent(),true); mailSender.send(mimeMessage); System.out.print("发送完成!"); } }
package cn.bdqn; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.bdqn.service.LeaveService; public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); LeaveService service = (LeaveService)context.getBean("leaveService"); service.updateLeave(); } }
4.最简单的站内传送Email上传,不需要大配置、log4j、架包
package cn.happy.mailjames; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class EmailAuthenticator extends Authenticator { private String username; private String userpass; public void setUsername(String username) { this.username = username; } public void setUserpass(String userpass) { this.userpass = userpass; } public EmailAuthenticator() { } public EmailAuthenticator(String username, String userpass) { this.username = username; this.userpass = userpass; } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username,userpass); } }
package cn.happy.mailjames; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail { private String mailServer,from,to,mailSubject,mailContent; private String username,password; public Mail(){ //设置邮件信息 //进行认证登录的用户名 username="wxk@mail.com"; //认证密码 password="wxk"; //认证的邮箱对应的邮件服务器 mailServer="192.168.8.71"; //发件人信息 from="wxk"; //收件人信息 to="wj@mail.com"; //邮件标题 mailSubject="记录成长的每一个脚印,写下漫长的程序人生"; //邮件内容 mailContent="这是一封测试邮件!如有雷同,纯属不可能"; } //设置邮件服务器 @SuppressWarnings("static-access") public void send(){ Properties prop=System.getProperties(); //指定邮件server prop.put("mail.smtp.host", mailServer); //是否开启认证 prop.put("mail.smtp.auth", "true"); //smtp协议的 prop.put("mail.smtp.port", "25"); //产生Session服务 EmailAuthenticator mailauth=new EmailAuthenticator(username, password); Session mailSession=Session.getInstance(prop,(Authenticator)mailauth); try { //封装Message对象 Message message=new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); //发件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人 message.setSubject(mailSubject); //设置内容(设置字符集处理乱码问题) message.setContent(mailContent,"text/html;charset=gbk"); message.setSentDate(new Date()); //创建Transport实例,发送邮件 Transport tran=mailSession.getTransport("smtp"); tran.send(message,message.getAllRecipients()); tran.close(); } catch (Exception e) { e.printStackTrace(); } } }
package cn.happy.mailjames; public class Test { public static void main(String[] args) { Mail mail=new Mail(); mail.send(); System.out.println("success!"); } }