1、什么是java mail
JAVA MAIL是利用现有的邮件账户发送邮件的工具,通过JAVA Mail的操控,让程序自动的使用设置的邮箱发送邮件。
这一机制被广泛的用在注册激活和垃圾邮件的发送等方面。
2、邮件发送的大致过程
1、构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法。
此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。
2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。
3、通过构建的properties文件和javax.mail.Authenticator具体类来创建一个javax.mail.Session。
Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。
4、构建邮件内容,一般是javax.mail.internet.MimeMessage对象,并指定发送人,收信人,主题,内容等等。
5、使用javax.mail.Transport工具类发送邮件。
3、准备工作
下载JavaMail jar包,导入工程。
http://www.oracle.com/technetwork/java/javamail/index-138643.html
4、案例代码
MyEmailAutherticator.java
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyEmailAutherticator extends Authenticator { //用户名(登录邮箱) private String username; //密码 private String password; public MyEmailAutherticator() { super(); } //初始化邮箱和密码 public MyEmailAutherticator(String username, String password) { this.username = username; this.password = password; } //用作登录校验,以确保对该邮箱有发送邮件的权利 public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } //set and get method public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Mail.java
import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail { //发送邮件的帐号和密码 private String username="abc123456@qq.com"; private String password="xxxxxx"; private String host = "smtp.qq.com"; private String mail_head_name = "this is head of this mail"; private String mail_head_value = "this is head of this mail"; private String mail_to = "123456789@qq.com"; private String mail_from = "abc123456@qq.com"; private String mail_subject = "this is the subject of this test mail"; private String mail_body = "this is mail_body of this test mail"; private String personalName = "我的邮件"; public void sendMail() throws SendFailedException{ try { //发送邮件的props文件 Properties props = new Properties(); // 初始化props props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); System.out.println(props); //进行邮件服务用户认证 Authenticator auth = new MyEmailAutherticator(username,password); // 创建session,和邮件服务器进行通讯 Session session = Session.getDefaultInstance(props,auth); // 创建mime类型邮件 MimeMessage message = new MimeMessage(session); //设置邮件格式 message.setContent("Hello","text/html;charset=utf-8"); // 设置主题 message.setSubject(mail_subject); //设置邮件内容 message.setText(mail_body); //设置邮件标题 message.setHeader(mail_head_name, mail_head_value); message.setSentDate(new Date());//设置邮件发送时期 Address address = new InternetAddress(mail_from,personalName); //设置邮件发送者的地址 message.setFrom(address); //======单发邮件====== //设置邮件接收者的地址 Address toaddress = new InternetAddress(mail_to); // 设置收件人 message.addRecipient(Message.RecipientType.TO,toaddress); //======群发邮件====== // List<String> recipients = new ArrayList<String>(); // recipients.add("123456789@qq.com"); // recipients.add("234567890@gmail.com"); // final int num = recipients.size(); // InternetAddress[] addresses = new InternetAddress[num]; // for (int i = 0; i < num; i++) { // addresses[i] = new InternetAddress(recipients.get(i)); // } // message.setRecipients(Message.RecipientType.TO, addresses); System.out.println(message); // 发送邮件 Transport.send(message); System.out.println("Send Mail Ok!"); } catch (Exception e) { e.printStackTrace(); } } }
Test.java
public class Test { public static void main(String[] args) { Mail m = new Mail(); try { m.sendMail(); } catch (Exception e) { } } }
2015-8-6补充代码
public class Demo1 { @Test public void fun1() throws Exception { /* * 1. 得到session */ Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("itcast_cxf", "itcast"); } }; Session session = Session.getInstance(props, auth); /* * 2. 创建MimeMessage */ MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//设置发件人 msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//设置收件人 msg.setRecipients(RecipientType.CC, "itcast_cxf@sohu.com");//设置抄送 msg.setRecipients(RecipientType.BCC, "itcast_cxf@sina.com");//设置暗送 msg.setSubject("这是来自ITCAST的测试邮件"); msg.setContent("这就是一封垃圾邮件!", "text/html;charset=utf-8"); /* * 3. 发 */ Transport.send(msg); } /** * 带有附件的邮件!!! */ @Test public void fun2() throws Exception { /* * 1. 得到session */ Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("itcast_cxf", "itcast"); } }; Session session = Session.getInstance(props, auth); /* * 2. 创建MimeMessage */ MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//设置发件人 msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//设置收件人 msg.setSubject("这是来自ITCAST的测试邮件有附件"); //////////////////////////////////////////////////////// /* * 当发送包含附件的邮件时,邮件体就为多部件形式! * 1. 创建一个多部件的部件内容!MimeMultipart * MimeMultipart就是一个集合,用来装载多个主体部件! * 2. 我们需要创建两个主体部件,一个是文本内容的,另一个是附件的。 * 主体部件叫MimeBodyPart * 3. 把MimeMultipart设置给MimeMessage的内容! */ MimeMultipart list = new MimeMultipart();//创建多部分内容 // 创建MimeBodyPart MimeBodyPart part1 = new MimeBodyPart(); // 设置主体部件的内容 part1.setContent("这是一封包含附件的垃圾邮件", "text/html;charset=utf-8"); // 把主体部件添加到集合中 list.addBodyPart(part1); // 创建MimeBodyPart MimeBodyPart part2 = new MimeBodyPart(); part2.attachFile(new File("F:/f/白冰.jpg"));//设置附件的内容 part2.setFileName(MimeUtility.encodeText("大美女.jpg"));//设置显示的文件名称,其中encodeText用来处理中文乱码问题 list.addBodyPart(part2); msg.setContent(list);//把它设置给邮件作为邮件的内容。 //////////////////////////////////////////////////////// /* * 3. 发 */ Transport.send(msg); } }