JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件。这一机制被广泛的用在注册激活和垃圾邮件的发送等方面。
JavaMail可以到http://www.oracle.com/technetwork/java/javamail/index-138643.html进行下载,并将mail.jar添加到classpath即可。如果你使用的是JAVA EE SDK,则可以在C:\glassfishv3\glassfish\modules\mail.jar找到所需的jar包,同样需要添加的classpath。
第一步:
注册网易邮箱
第二步:
需要开启SMTP协议
第三步:
书写邮件发送代码
public class MailService{
public static final String HOST = "smtp.163.com";
public static final String PROTOCOL = "smtp";
public static final int PORT = 25;
public static boolean sendMail(String subject, String toMail,String content, String... files) {
boolean isFlag = false;
try {
//邮箱账号
String smtpFromMail = "***********@163.com"; //密码(不是你注册邮箱登录密码)
String pwd = "ziupkzexofqavuoo";
int port = 25;
String host = "smtp.163.com";
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.store.protocol" , PROTOCOL);
props.put("mail.smtp.port", PORT);
props.put("mail.smtp.auth" , true);
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(smtpFromMail, "QQ"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toMail));
message.setSubject(subject);
message.addHeader("charset", "UTF-8");
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(content);
contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
multipart.addBodyPart(contentPart);
for (String file : files) {
File usFile = new File(file);
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new FileDataSource(file);
fileBody.setDataHandler(new DataHandler(source));
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
fileBody.setFileName("UTF-8"
+ enc.encode(usFile.getName().getBytes()) + "?=");
multipart.addBodyPart(fileBody);
}
message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, port, smtpFromMail, pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isFlag = true;
} catch (Exception e) {
e.printStackTrace();
isFlag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return isFlag;
} //写个主函数去测试
public static void main(String[] args) {//标题:你好;接收者:**********@qq.com;内容:测试
MailService.sendMail("你好", "**********@qq.com", "测试");
}
}
第四步:
剩下的就是去查看邮件是否发送成功了。呼呼~~
第五步:
去垃圾邮件中查找你刚才测试邮件:那是应为你接收的邮件过多,系统会默认把这些邮件当做垃圾邮件