不多说,直接上代码
/**
* 发送邮件
* @param subject 主题
* @param to 收件人
* @param username 邮箱账号
* @param password 邮箱密码
* @param host 邮件服务器
* @param content 邮件内容
* @param isAuth 是否验证密码
*/
public void send(String subject, String to,String username, String password, String host, String content,boolean isAuth) {
try{
String[] mailArray = to.split(";");
//多个收件人
InternetAddress[] addresses = new InternetAddress[mailArray.length];
for(int i=0;i<mailArray.length;i++){
addresses[i] = new InternetAddress(mailArray[i]);
}
//创建properties,用于生成发送邮件的session
Properties properties = new Properties();
properties.put("mail.smtp.host", host); //发送邮件的主机
properties.put("mail.smtp.auth", isAuth); //是否验证发送人密码
properties.put("mail.smtp.port", 25); //端口
//通过配置文件,生成一个session
Session mailSession = Session.getInstance(properties,null);
mailSession.setDebug(true);
//通过session开始创建message
MimeMessage mailMessage = new MimeMessage(mailSession);
设置发件人,使用InternetAddress
mailMessage.setFrom(new InternetAddress(username));
//收件人,这里为多个
mailMessage.setRecipients(MimeMessage.RecipientType.TO, addresses);
mailMessage.setSubject(subject); //邮件主题
//Multipart用来防止邮件内容,其中可放多个BodyPart
Multipart multipart = new MimeMultipart();
//第一个bodypart,放置普通文字吧
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(content, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//第二个bodypart,放置附件吧
BodyPart p_w_uploadBodyPart = new MimeBodyPart();
//附件文件,需要用DataSource来构造对象
DataSource source = new FileDataSource("E:/students.xls");
//DataSource需要用DataHandler来构造
p_w_uploadBodyPart.setDataHandler(new DataHandler(source));
p_w_uploadBodyPart.setFileName("students.xls");//附件文件名
multipart.addBodyPart(p_w_uploadBodyPart);
mailMessage.setContent(multipart); //将内容设置给message
mailMessage.setSentDate(new Date()); //发送时间
mailMessage.saveChanges();
if(isAuth){
Transport.send(mailMessage, username, password);
}else{
Transport.send(mailMessage); //Transport开始发送邮件
}
}catch(Exception e){
try {
throw e;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
简单的写一个main方法
public static void main(String arg[]) {
Mail mail = new Mail();
//主题,收件人,发件人,密码,邮件服务器。。。。。。。
mail.send("测试1", "jun.xie@chinacache.com", "ren.shi@chinacache.com", "123456", "mail.chinacache.com", "testdfdf", false);
}
转载于:https://blog.51cto.com/5148737/1587624