码迷,mamicode.com
首页 > 编程语言 > 详细

javax.mail 发邮件时添加附件

时间:2015-04-13 09:49:41      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.Properties;


import javax.mail.Authenticator;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;


public class TestEmail {

/**

* @param host 邮箱发件服务器

* @param userName 发送人用户名,一般是邮箱名

* @param password 邮箱密码

* @param receive 收件人邮箱地址

* @throws Exception

*/

public static void sendMail(String host,final String userName,final String password,String receive) throws Exception{

Properties props = new Properties();

props.put("mail.smtp.host", host);

props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, new Authenticator(){protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName,password);

}});

MimeMessage m = new MimeMessage(session);

m.setFrom(new InternetAddress(userName,"huhao"));

m.setRecipients(Message.RecipientType.TO, receive);

//主题

m.setSubject("hello3");

// m.setText("nihao1");

//正文内容

Multipart mp = new MimeMultipart();

BodyPart body = new MimeBodyPart();

body.setText("hello ,hu   hao");

mp.addBodyPart(body);

//附件一

MimeBodyPart bp = new MimeBodyPart();

//添加附件路径

bp.attachFile("D:/txt.txt");

mp.addBodyPart(bp,1);

//附件二

MimeBodyPart bp1 = new MimeBodyPart();

bp1.attachFile("D:/1.jpg");

mp.addBodyPart(bp1,2);

m.setContent(mp);

Transport.send(m);

}

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

String host = "";//例如qq邮箱smtp.qq.com

String userName = "";

String password = "";

String receive = "";

TestEmail.sendMail(host,userName,password,receive);

}

}


javax.mail 发邮件时添加附件

标签:

原文地址:http://my.oschina.net/hu382337381/blog/399368

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!