您的位置:首页 > 编程语言 > Java开发

Java Mail实现发送带附件的邮件

2017-01-23 10:58 465 查看
使用的jar包mail-1.4.7.jar ,相应的API 参考
点击

先设计一个组装邮件实体的MailInfo类

// 端口
private String port;
// 邮箱服务器 如smtp.xxx.xxx
private String host;
// 用户邮箱 如
private String formName;
// 用户授权码 或者密码
private String formPassword;
// 消息回复邮箱
private String replayAddress;
// 发送地址
private Address[] toAddress;
// 发送主题
private String subject;
// 发送内容
private String content;
// 抄送人
private Address[] toCCs;
// 密送
private Address[] toBCC;

public MailInfo() {
if (content == null) {
this.content = "";
}
}


直接贴上发送的方法,基本都写好注释了,封装的不好,欢迎留言指正

public class MailSendUtil {

private final static String host = "smtp.xx.com"; //smtp的服务器
private final static String port = "xx"; //端口
private final static String formName = "xxxx";  //你的邮箱
private final static String password = "xxxx"; //授权码或者密码,qq和163需要授权码,而非邮箱密码
private final static String replayAddress = "xxxx"; //你的邮箱

/* public static void sendTextMail() throws Exception {
MailInfo info = new MailInfo();
info.setToAddress("xxx");
info.setHost(host);
info.setPort(port);
info.setFormName(formName);
info.setFormPassword(password);   //
info.setReplayAddress(replayAddress);
Message message = getMessage(info);
//消息发送的内容
message.setText("邮件发送成功了");

Transport.send(message);
}*/

/**
* 组装邮件实体
* @param subject
* @return
* @throws AddressException
*/
@SuppressWarnings("static-access")
public static MailInfo addMailInfo(String subject) throws AddressException{
MailInfo info = new MailInfo();
info.setHost(host);
info.setPort(port);
info.setFormName(formName);
info.setFormPassword(password);
info.setReplayAddress(replayAddress);
info.setToAddress(new InternetAddress().parse("xxxx@qq.com,jfzf@qq.com")); //必须是以,分割   否则会异常
info.setToCCs(new InternetAddress().parse("jfz@live.com"));
info.setToBCC(new InternetAddress().parse("jjff@sina.cn"));
info.setSubject(subject);
return info;
}

private static Message getMessage(MailInfo info) throws Exception{
final Properties p = System.getProperties() ;
p.setProperty("mail.smtp.host", info.getHost());
//p.setProperty("mail.transport.protocol", "smtp");
p.setProperty("mail.smtp.auth", "true");
p.setProperty("mail.smtp.user", info.getFormName());
p.setProperty("mail.smtp.pass", info.getFormPassword());
p.setProperty("mail.smtp.port", info.getPort());
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(p, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
}
});
session.setDebug(true);
Message message = new MimeMessage(session);
//消息发送的主题
message.setSubject(info.getSubject());
//接受消息的人
message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
//消息的发送者
message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"Mr.Phil"));
//发送地址
message.addRecipients(Message.RecipientType.TO, info.getToAddress());
//抄送地址
message.addRecipients(Message.RecipientType.CC, info.getToCCs());
//密送地址
message.addRecipients(Message.RecipientType.BCC,info.getToBCC());
// 消息发送的时间
message.setSentDate(new Date());
return message ;
}

/**
* 添加单个的接收人邮箱
* @param recipient
* @throws MessagingException
*/
public static void addToRecipient(Message message, String recipient) throws MessagingException{
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

}

/**
* 添加多个的接收人邮箱
* @param recipient
* @throws MessagingException
*/
@SuppressWarnings("static-access")
public static void addToRecipients(Message message, String recipients) throws MessagingException{
Address []address = new InternetAddress().parse(recipients);
message.addRecipients(Message.RecipientType.TO, address);
}

/**
* 添加内容
* @param multipart
* @param content
* @throws MessagingException
*/
public static void addContent(Multipart multipart, String content) throws  MessagingException{
if(content==null){
content = "";
}
BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(content,"text/html; charset=utf-8");
multipart.addBodyPart(bodypart);
}

/**
* 添加附件
* @param multipart
* @param filePaths
* @throws IOException
* @throws MessagingException
*/
public static void addAttach(Multipart multipart, List<String> filePaths) throws IOException, MessagingException{
if(filePaths!=null && filePaths.size()>0){
for(String path : filePaths){
File file = new File(path);
if(!file.exists()){
throw new IOException("文件不存在!请确定文件路径是否正确");
}
BodyPart bodypart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(dataSource));
//防止文件出现乱码
bodypart.setFileName(MimeUtility.encodeText(file.getName()));
multipart.addBodyPart(bodypart);
}
}
}
/**
* 发送方法
* @throws Exception
*/
public static void sendHtmlMail()throws Exception{
MailInfo info = addMailInfo("这是一封测试邮件,请勿回复");
Message message = getMessage(info);
Multipart mainPart = new MimeMultipart();
//邮件邮件内容
addContent(mainPart, "这是一个超链接,点击是<a href=\"http://www.qq.com\">腾讯首页</a>");
List<String> ls = new ArrayList<>();
ls.add("C://Users/fjing/Desktop/主机信息.txt");
addAttach(mainPart, ls);
//将mainPart对象设置为邮件内容
message.setContent(mainPart);
Transport.send(message);
}

public static void main(String[] args) throws Exception{
sendHtmlMail();
}
}


目前总结的,新浪和微软不需要加端口,网易和QQ需要加端口,其他没测试过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: