编程爱好者联盟 2016-11-04
James是Apache的一个开源项目,纯Java实现,Apache james Server作为一个企业级的邮件服务器,对SMTP,POP3,IMAP等邮件协议提供完整的支持。
1.搭建James服务器
Apache James 的官方网站为:http://james.apache.org/,当前 Server 的最新版为 2.3.2版. 安装非常简单,下载后得到apache-james-2.3.2.zip 文件,解压后即可。
在James的bin目录中包含两个重要文件run.bat和run.sh,运行run.bat就可以轻松地启动James邮件服务器。
启动后能在控制台看到如下信息,说明启动成功:
说明:启动前请确保您的JDK环境变量如JAVA_HOME等已经设置好;James 启动时,其SMTP 服务默认在 25 端口启动,POP3 服务默认在 110 端口启动, NNTP 服务默认在 119 端口启动, 请确保这些端口未被占用。比如本系统下就已经安装了Microsoft的 SMTP 服务,造成 James无法启动,解决方法为:开始--->设置--->控制面板--->管理工具--->服务,打开后找到“Simple Mail Transport Protocol(SMTP)”服务项,关闭即可。
5。配置服务
服务器启动后会在本机配置一个默认的服务,这可以用来在本机上本服务器范围内收发邮件,但是邮件发不到163等外网邮箱。我们这里关注的重点就是配置一个能发到外网如163这样的邮箱的邮件,这样才有价值。不过由于本人是在本机上测试,一时不能获取公司的域名参数,无法测试接收外网邮箱(如163)的邮件,见晾,不过做法都是一样的,至少我们可以向外网邮箱发送邮件,局域网内可以收、发邮件。
打开D:\james-2.3.1\apps\james\SAR-INF 下的 config.xml 文件,初次启动James之前,不会有这个文件,只有当James服务启动一次之后才自动构件该文件。
<postmaster>Postmaster@localhost</postmaster> …… <servernames autodetect="true" autodetectIP="true"> <servername>localhost</servername> </servernames>
把localhost该成你自己想要的邮箱域名, 把自动探测IP属性设置为“false”这里假设改成 mail.com ,那么他的邮件地址就是 mail.com修改结果如下:
<postmaster>[email protected]</postmaster> …… <servernames autodetect="false" autodetectIP="false"> <servername>mail.com</servername> </servernames>
3.创建邮件帐号
使用telnet连接James的Remote Administration Tool。打开一个控制台窗口,输入telnet smtp.163.com
JAMES Remote Administration Tool 2.3.1 Please enter your login and password Login id: root Password: root Welcome root. HELP for a list of commands
创建新用户的命令是:adduser username password
提示用户可以通过“HELP”命令来查询suo9支持的所有命令
help display this help 显示帮助信息 listusers display existing accounts 显示现有账户 countusers display the number of existing accounts 显示现有账户数量 adduser [username] [password] add a new user 添加一个新用户 verify [username] verify if specified user exist 核实指定用户是否存在 deluser [username] delete existing user 删除存在的用户 setpassword [username] [password] sets a user's password 设置用户密码 setalias [user] [alias] locally forwards all email for 'user' to 'alias' 设置邮箱别名 showalias [username] shows a user's current email alias 显示别名 unsetalias [user] unsets an alias for 'user' 删除用户别名 setforwarding [username] [emailaddress] forwards a user's email to another email address 转发用户的电子邮件地址到另一个电子邮件地址 showforwarding [username] shows a user's current email forwarding 显示用户的当前邮件转发 unsetforwarding [username] emoves a forward 删除转发 user [repositoryname] change to another user repository 改变另一个用户库 shutdown kills the current JVM (convenient when James is run as a daemon)关闭当前的服务 quit close connection 关闭连接
示例:
public class Mail { private String mailServer,from,to,mailSubject,mailContent; private String username,password; public Mail(){ //设置邮件信息 //进行认证登录的用户名 username="[email protected]"; //认证密码 password="456"; //认证的邮箱对应的邮件服务器 mailServer="smtp.163.com"; //发件人信息 from="[email protected]"; //收件人信息 to="[email protected]"; //邮件标题 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(); } } }
使用Spring发送电子邮件
创建SimpleMailMessage
SimpleMailMessage是MailMessage接口的实现类之一。
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("[email protected]"); message.setTo("tom"); message.setSubject("问好"); message.setText("好久不见,最近好吗?"); mailSender.send(message); } }
applicationContext.xml
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="192.168.15.22"></property><!-- 服务器 --> <property name="port" value="25"></property><!-- 端口 --> <property name="username" value="[email protected]"></property><!-- 用户名 --> <property name="password" value="dzw"></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="mail" class="cn.bdqn.Mail"> <property name="mailSender" ref="mailSender"></property> </bean> <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment"> <property name="mailSender" ref="mailSender"></property> </bean> <bean id="mailWithHtml" class="cn.bdqn.MailWithHTML"> <property name="mailSender" ref="mailSender"></property> </bean> </beans>
发送HTML格式的电子邮件
HTMl格式的文本属于MIME类型,需要MimeMessageHelper类的支持
public class MailWithHTML { 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("[email protected]"); helper.setTo("tom"); helper.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='5' face='Arial'>"); sb.append("尊敬的jerry您好:</font><br/><br/>"); sb.append(" "); sb.append("<font color='black' size='4' face='Arial'>"); sb.append("恭喜您在员工社区注册账号成功!请妥善保管您的账号," + "如果登录时忘记密码,可以在网站登录页找回。<br/>"); sb.append("<br/><br/>系统管理员</font>"); //增加内嵌图片设置 sb.append("<br/><img src=\"cid:photo\"></img>"); sb.append("</body></html>"); helper.setText(sb.toString(),true); //增加内嵌文件 ClassPathResource file = new ClassPathResource("/cn/bdqn/attachfiles/Quartz.png"); helper.addInline("photo", file); mailSender.send(mimeMessage); } }
通过setText()设置html参数为true,邮件内容就可以显示HTML页面。在HTML页面中,需要设置content属性,通过“text/html;charset=utf-8”
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("[email protected]"); helper.setTo("tom"); helper.setSubject("问好"); helper.setText("好久不见,最近好吗?"); //添加附件1 ClassPathResource file1 = new ClassPathResource( "/cn/bdqn/attachfiles/test.doc"); 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); } }
测试类
public class MailTest { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /*测试简单邮件*/ Mail mail = (Mail)context.getBean("mail"); mail.send(); /*测试带附件的邮件*/ try{ MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment"); mailWithAttach.send(); }catch(Exception e){ System.out.print(e.toString()); } /*测试HTML格式的邮件*/ try{ MailWithHTML mailWithHtml = (MailWithHTML)context.getBean("mailWithHtml"); mailWithHtml.send(); }catch(Exception e){ System.out.print(e.toString()); } } }