使用免费的邮件服务器发送邮件时,需要对用户的身份做验证;而进行身份验证的过程又比较消耗时间,当用户需要发送多封邮件时如果每次都做身份验证的话时间的消耗是非常大的;
邮件格式最好清晰,较为常见的收发邮件的服务器而且做得笔记好的就是163的smtp、pop3,当然了QQ腾讯的也不错。
邮件开始发送的验证有点繁琐,格式不对或者带有特殊字符的都会被他们的服务器过滤掉,
所以,为了避免他们把你的发件箱作为垃圾邮件屏蔽掉的话,最好避开这些 :一个账号发送大量邮件、相同IP短期发送大量邮件 、发送邮件速度太快、邮件导出链接数太多、软件设置过度、邮件标题过于敏感、邮件内容够多而且重复等等!
下面列出一个用163的账号来发送邮件(可以添加一个附件)的例子,当然还可以访问收件箱里面的邮件,把对应的邮件标签设置成为已读、已删除等等,这里就不多说了....
private MimeMessage mimeMsg;//整个MIME邮件对象
private Session session;//专门用来发送邮件的Session会话
private Properties props;//封装邮件发送时的一些配置信息的一个属性对象
private static String username="xxxx@163.com";//发件人的用户名
private static String password="xxxx"; //发件人的密码
private Multipart mp; //用来实现附件添加的组件
public EmailServer(String smtp){
setSmtpHost(smtp);
createMimeMessage();
}
public void setSmtpHost(String hostName){
System.out.println("设置系统属性:mail.smtp.host = " + hostName);
if (props == null)
props = System.getProperties();
props.put("mail.smtp.host", hostName);
}
public boolean createMimeMessage(){
try{
System.out.println("准备获取邮件会话对象!");
// 用props对象来创建并初始化session对象
session = Session.getDefaultInstance(props, null);
}catch (Exception e){
System.err.println("获取邮件会话对象时发生错误!" + e);
return false;
}
System.out.println("准备创建MIME邮件对象!");
try{
mimeMsg = new MimeMessage(session);
mp = new MimeMultipart();
}catch (Exception e){
System.err.println("创建MIME邮件对象失败!" + e);
return false;
}
return true;
}
public void setNeedAuth(boolean need){
System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);
if (props == null){
props = System.getProperties();
}
if (need)
props.put("mail.smtp.auth", "true");
else
props.put("mail.smtp.auth", "false");
}
public void setNamePass(String name, String pass){
System.out.println("程序得到用户名与密码");
username = name;
password = pass;
}
public boolean setSubject(String mailSubject){
System.out.println("设置邮件主题!");
try{
mimeMsg.setSubject(mailSubject);
}
catch (Exception e){
System.err.println("设置邮件主题发生错误!");
return false;
}
return true;
}
public boolean setBody(String mailBody){
try{
System.out.println("设置邮件体格式");
BodyPart bp = new MimeBodyPart();
bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>" + mailBody,
"text/html;charset=UTF-8");
// 在组件上添加邮件文本
mp.addBodyPart(bp);
}catch (Exception e){
System.err.println("设置邮件正文时发生错误!" + e);
return false;
}
return true;
}
/**
* 增加发送附件
*
* @param filename
* 邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常
* @return
*/
public boolean addFileAffix(String filename){
System.out.println("增加邮件附件:" + filename);
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
// 发送的附件前加上一个用户名的前缀
bp.setFileName(filename);
// 添加附件
mp.addBodyPart(bp);
}
catch (Exception e){
System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
return false;
}
return true;
}
public boolean setFrom(String nick,String from){
try{
mimeMsg.setFrom(new InternetAddress(nick+" <"+username+">"));
}catch (Exception e){
return false;
}
return true;
}
/**
* 设置收件人地址
*
* @param to
* 收件人的地址
* @return
*/
public boolean setTo(String to){
System.out.println("设置收信人");
if (to == null)
return false;
try{
mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
}catch (Exception e){
return false;
}
return true;
}
/**
* 发送附件
*
* @param copyto
* @return
*/
public boolean setCopyTo(String copyto){
System.out.println("发送附件到");
if (copyto == null)
return false;
try{
mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(copyto));
}catch (Exception e){
return false;
}
return true;
}
/**
* 发送邮件
*
* @return
*/
public boolean sendout(){
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
// 真正的连接邮件服务器并进行身份验证
transport.connect((String) props.get("mail.smtp.host"), username, password);
// 发送邮件
transport.sendMessage(mimeMsg, mimeMsg.getRecipients(javax.mail.Message.RecipientType.TO));
System.out.println("发送邮件成功!");
transport.close();
}catch (Exception e){
System.err.println("邮件发送失败!" + e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
//发送邮件。业务逻辑处理 注册 找回密码 付款成功
@SuppressWarnings("unchecked")
public static boolean sendUserEmail(String Emailtitle,String userEmail,String filename){
boolean falg = false;
EmailServer themail = new EmailServer("smtp.163.com");
themail.setNeedAuth(true);
StringBuffer mailbody = new StringBuffer("");
themail.setBody(mailbody.toString());
themail.setSubject(Emailtitle);
themail.setTo(userEmail);
//设置超值网发件人昵称
String nick = "";
try {
nick=javax.mail.internet.MimeUtility.encodeText("xxxxx: ");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
themail.addFileAffix(filename);
//收件人地址
themail.setFrom(nick,username);
themail.setNamePass(username, password);
if(themail.sendout()){
falg=true;
}
return falg;
}
public static void main(String[] args) {
EmailServer.sendUserEmail("title", "xxx@qq.com","D:/logs/aaa.log");
}
注意!在初始化EmailServer对象时千万不要设置成静态块,不然你接下来发送的附近就莫名其妙了!