最近没事做,写了一个简单的邮件发送实例..
首先做好, 准备工作..如果是JDK1.5则要准备如下两个包.
mail.jar
activation.jar
把这这两个包,添加到项目的依赖中..
接下来就是写Email 代码的部分:
具体代码如下:
/** * 邮件的基本配置信息; * @author Administrator * */ public class MailSenderInfo { //发送邮件服务器; private String emailServiceHost; //发送服务器端口; private String emailServicePort; //邮件发送者地址; private String fromAddress; //邮件接收地址; private String toAddress; //登陆邮件服务器的用户名; private String userName; //登陆邮件服务器的密码; private String password; //是否需要验证; private boolean validate; //邮件主题; private String subject; //邮件内容; private String content; //附件文件名; private String[] attachFileNames; //***getter 和 setter方法省略*** }
接下来封装发送邮件的方法.
public class SimpleMailSender {
/**
* 以文本的格式发送邮件;
* @return boolean;
*/
public boolean sendTextMail(MailSenderInfo mailSenderInfo){
//是否身份验证;
MyAuthenticator authenticator = null;
//获取邮件的配置信息;
Properties properties = new Properties();
properties.put("mail.smtp.host",mailSenderInfo.getEmailServiceHost());
properties.put("mail.smtp.auth", "true");
//判断是否身份验证;
if(mailSenderInfo.isValidate()){
//如果是需要身份验证,这创建一个密码验证器;
authenticator = new MyAuthenticator(mailSenderInfo.getUserName(), mailSenderInfo.getPassword());
}
//根据邮件 的用户名和密码创建一个发邮件的Session;
Session senderMailSession = Session.getDefaultInstance(properties,authenticator);
//根据session创建一个邮件消息;
Message mailMessage = new MimeMessage(senderMailSession);
try {
try {
//创建邮件发送者地址;
mailMessage.setFrom(new InternetAddress(mailSenderInfo.getFromAddress()));
//创建邮件接收者地址;
Address toAddress = new InternetAddress(mailSenderInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,toAddress);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//设置邮件主题;
mailMessage.setSubject(mailSenderInfo.getSubject());
//设置邮件发送时间:
mailMessage.setSentDate(new Date());
//设置邮件内容;设置这个. "text/html;charset=utf-8" 解决内容乱码问题..
mailMessage.setContent(mailSenderInfo.getContent(),"text/html;charset=utf-8");
//发送邮件;
Transport.send(mailMessage);
return true;
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
最后就是测试邮件发送:
public class EmailTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MailSenderInfo mailSenderInfo = new MailSenderInfo(); mailSenderInfo.setUserName("[email protected]"); mailSenderInfo.setPassword("88888"); mailSenderInfo.setEmailServiceHost("smtp.163.com"); mailSenderInfo.setValidate(true); mailSenderInfo.setFromAddress("[email protected]"); mailSenderInfo.setToAddress("[email protected]"); mailSenderInfo.setSubject("第一封邮件"); mailSenderInfo.setContent("first Email!"); SimpleMailSender sender = new SimpleMailSender(); boolean sendresult= sender.sendTextMail(mailSenderInfo); if(sendresult){ System.out.println("邮件发送成功!"); }else{ System.out.println("邮件发送失败!"); } } }
在测试时, 邮箱一定要设置开通smtp服务的, 像 126,163这些网易邮箱,是默认不开通..所以需要在设置->POP3/SMTP里面->把smtp服务勾选上..才可以。
还有一个就是,你的邮箱 用户名和 mail.smpt.host.地址要一致,.否则发不出去..
我整了好几个小时..才测试通过。所以今天特意写出来.. 希望大家不要遇到我同样的错误...少走弯路。