1 public class ApacheMailTest { 2 // smtp服务器 3 private String hostName = "smtp.qq.com"; 4 // 帐号与密码 5 private String userName = "779554589"; 6 private String password = "这是个秘密"; 7 // 发件人 8 private String fromAddress = "779554589@qq.com"; 9 // 发件人姓名 10 private String fromName = "loadfate"; 11 12 public static void main(String[] args) throws Exception { 13 // 收件人与收件人名字 14 String toAddress = "loadfate@163.com"; 15 String toName = "loadfate"; 16 ApacheMailTest test = new ApacheMailTest(); 17 // 所有的异常都为处理,方便浏览 18 19 test.sendSimpleEmail(toAddress, toName); 20 test.sendHtmlEmail(toAddress, toName); 21 test.sendMultiPartEmail(toAddress, toName); 22 System.out.println("发送完成"); 23 } 24 25 // 发送简单邮件,类似一条信息 26 public void sendSimpleEmail(String toAddress, String toName) throws Exception { 27 SimpleEmail email = new SimpleEmail(); 28 email.setHostName(hostName);// 设置smtp服务器 29 email.setAuthentication(userName, password);// 设置授权信息 30 email.setCharset("utf-8"); 31 email.setFrom(fromAddress, fromName, "utf-8");// 设置发件人信息 32 email.addTo(toAddress, toName, "utf-8");// 设置收件人信息 33 email.setSubject("测试主题");// 设置主题 34 email.setMsg("这是一个简单的测试!");// 设置邮件内容 35 email.send();// 发送邮件 36 } 37 38 // 发送Html内容的邮件 39 public void sendHtmlEmail(String toAddress, String toName) throws Exception { 40 HtmlEmail email = new HtmlEmail(); 41 email.setHostName(hostName); 42 email.setAuthentication(userName, password); 43 email.setCharset("utf-8"); 44 email.addTo(toAddress, toName, "utf-8"); 45 email.setFrom(fromAddress, fromName, "utf-8"); 46 email.setSubject("这是一个html邮件"); 47 // 设置html内容,实际使用时可以从文本读入写好的html代码 48 email.setHtmlMsg("<div style='width:100px;height:200px;'>a</div>"); 49 email.send(); 50 51 } 52 53 // 发送复杂的邮件,包含附件等 54 public void sendMultiPartEmail(String toAddress, String toName) throws Exception { 55 MultiPartEmail email = null; 56 email = new MultiPartEmail(); 57 email.setHostName(hostName); 58 email.setAuthentication(userName, password); 59 email.setCharset("utf-8"); 60 email.addTo(toAddress, toName, "utf-8"); 61 email.setFrom(fromAddress, fromName, "utf-8"); 62 email.setSubject("这是有附件的邮件"); 63 email.setMsg("<a href='#'>测试内容</a>"); 64 65 // 为邮件添加附加内容 66 EmailAttachment attachment = new EmailAttachment(); 67 attachment.setPath("D:\\邮件.txt");// 本地文件 68 // attachment.setURL(new URL("http://xxx/a.gif"));//远程文件 69 attachment.setDisposition(EmailAttachment.ATTACHMENT); 70 attachment.setDescription("描述信息"); 71 // 设置附件显示名字,必须要编码,不然中文会乱码 72 attachment.setName(MimeUtility.encodeText("邮件.txt")); 73 // 将附件添加到邮件中 74 email.attach(attachment); 75 email.send(); 76 } 77 } |