Javamail
1.与HTTP协议相同,收发右键也是需要协议的
SMTP:发邮件协议
POP3:收邮件协议
IMAP:收发右键协议
2.导包:
mail.jar
activation.jar
3.核心类:
(1)session
如果你得到了它,表示已经与服务器连接上了,与Connection的作用相似
得到session,需要使用session.getInstance(Properties,Authenticator);
Properties props=new Properties();
props.setProperty("mail.host","smtp.163.com");
props.setProperty("mail.smtp.auth","true");
Authenticator auth=new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("username","password");
}
};
Session.getInstance(props,auth);
(2).MimeMessage
它表示一个邮件对象,你可以调用它的setFrom(),设置发件人、设置收件人、设置主题、设置正文!
(3).TransPort
它只有一个功能:发邮件
案例如下:
(1)发送普通邮件
public void fun1() throws MessagingException {
//设置Properties
Properties prop=new Properties();
//两个头!
prop.setProperty("mail.host","smtp.163.com");
prop.setProperty("mail.smtp.auth","true");
//账号密码
Authenticator auth=new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("","");
}
};
//session需要两个参数,Properties和Authenticator
Session session=Session.getInstance(prop,auth);
MimeMessage msg=new MimeMessage(session);
//From需要和上面的账号密码一致
msg.setFrom(new InternetAddress(""));
msg.setRecipients(Message.RecipientType.TO,"");
msg.setSubject("厉害");
msg.setContent("这是一封厉害的邮件","text/html;charset=utf-8");
//发送!!!
Transport.send(msg);
}
2.发送带附件的邮件!
注意:需要用到 MimeMultipart
@Test
public void fun2() throws MessagingException, IOException {
Properties prop=new Properties();
prop.setProperty("mail.host","smtp.163.com");
prop.setProperty("mail.smtp.auth","true");
Authenticator auth=new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("","");
}
};
//Session创建,需要两个参数
Session session=Session.getInstance(prop,auth);
//传概念MimeMessage
MimeMessage msg=new MimeMessage(session);
msg.setFrom(new InternetAddress(""));
msg.setRecipients(Message.RecipientType.TO,"");
msg.setSubject("哈哈邮件");
//内容部分需要稍作修改
//先创建MimeMultipart,来存储body
MimeMultipart multipart=new MimeMultipart();
//创建body1
MimeBodyPart mbp1=new MimeBodyPart();
mbp1.setContent("厉害了","text/html;charset=utf-8");
multipart.addBodyPart(mbp1);
//创建body2
MimeBodyPart mbp2=new MimeBodyPart();
mbp2.attachFile(new File("d:/a.jpg"));
//MimeUtility.decodeText设置编码格式!!
mbp2.setFileName(MimeUtility.decodeText("厉害图片.jpg"));
multipart.addBodyPart(mbp2);
msg.setContent(multipart);
//发送邮件
Transport.send(msg);
}
(3)利用MailUtils包便捷发送邮件
@Test
public void fun3() throws IOException, MessagingException {
Session session=MailUtils.createSession("smtp.163.com","","");
Mail mail=new Mail("","","什么邮件","没有什么邮件");
//添加附件
AttachBean ab1=new AttachBean(new File("d:/baibing.jpg"),"厉害了.jpg");
AttachBean ba2=new AttachBean(new File("d:/a.jpg"),"不厉害.jpg");
mail.addAttach(ab1);
mail.addAttach(ba2);
MailUtils.send(session,mail);
}