yuandan 发表于 2017-12-25 06:24:41

Android Java Mail与Apache Mail发送邮件对比

public>
// smtp服务器  
private String hostName = "smtp.qq.com";
  
// 帐号与密码
  
private String userName = "779554589";
  
private String password = "这是个秘密";
  
// 发件人
  
private String fromAddress = "779554589@qq.com";
  
// 发件人姓名
  
private String fromName = "loadfate";
  

  
public static void main(String[] args) throws Exception {
  
// 收件人与收件人名字
  
String toAddress = "loadfate@163.com";
  
String toName = "loadfate";
  
ApacheMailTest test = new ApacheMailTest();
  
// 所有的异常都为处理,方便浏览
  

  
test.sendSimpleEmail(toAddress, toName);
  
test.sendHtmlEmail(toAddress, toName);
  
test.sendMultiPartEmail(toAddress, toName);
  
System.out.println("发送完成");
  
}
  

  
// 发送简单邮件,类似一条信息
  
public void sendSimpleEmail(String toAddress, String toName) throws Exception {
  
SimpleEmail email = new SimpleEmail();
  
email.setHostName(hostName);// 设置smtp服务器
  
email.setAuthentication(userName, password);// 设置授权信息
  
email.setCharset("utf-8");
  
email.setFrom(fromAddress, fromName, "utf-8");// 设置发件人信息
  
email.addTo(toAddress, toName, "utf-8");// 设置收件人信息
  
email.addCc(xxx, xxx);//设置抄送
  
email.addBcc(xxx, xxx);//设置密送
  
email.setSubject("测试主题");// 设置主题
  
email.setMsg("这是一个简单的测试!");// 设置邮件内容
  
email.send();// 发送邮件
  
   }
  

  
// 发送Html内容的邮件
  
public void sendHtmlEmail(String toAddress, String toName) throws Exception {
  
HtmlEmail email = new HtmlEmail();
  
email.setHostName(hostName);
  
email.setAuthentication(userName, password);
  
email.setCharset("utf-8");
  
email.addTo(toAddress, toName, "utf-8");
  
email.addCc(xxx, xxx);//设置抄送
  
email.addBcc(xxx, xxx);//设置密送
  
email.setFrom(fromAddress, fromName, "utf-8");
  
email.setSubject("这是一个html邮件");
  
// 设置html内容,实际使用时可以从文本读入写好的html代码
  
email.setHtmlMsg("<div style='width:100px;height:200px;'>a</div>");
  
email.send();
  

  
}
  

  
// 发送复杂的邮件,包含附件等
  
public void sendMultiPartEmail(String toAddress, String toName) throws Exception {
  
MultiPartEmail email = null;
  
email = new MultiPartEmail();
  
email.setHostName(hostName);
  
email.setAuthentication(userName, password);
  
email.setCharset("utf-8");
  
email.addTo(toAddress, toName, "utf-8");
  
email.addCc(xxx, xxx);//设置抄送
  
email.addBcc(xxx, xxx);//设置密送
  
email.setFrom(fromAddress, fromName, "utf-8");
  
email.setSubject("这是有附件的邮件");
  
email.setMsg("<a href='#'>测试内容</a>");
  

  
// 为邮件添加附加内容
  
EmailAttachment attachment = new EmailAttachment();
  
attachment.setPath("D:\\邮件.txt");// 本地文件
  
// attachment.setURL(new URL("http://xxx/a.gif"));//远程文件
  
         attachment.setDisposition(EmailAttachment.ATTACHMENT);
  
attachment.setDescription("描述信息");
  
// 设置附件显示名字,必须要编码,不然中文会乱码
  
attachment.setName(MimeUtility.encodeText("邮件.txt"));
  
// 将附件添加到邮件中
  
         email.attach(attachment);
  
email.send();
  
}
  
}
页: [1]
查看完整版本: Android Java Mail与Apache Mail发送邮件对比