java代码发邮件和附件 java发送邮件附件( 二 )


* 输入参数 br
* 返回类型
*/
public void setContent(String content) {
ntent = content;
}
/**
* br
* 方法说明 把主题转换为中文 br
* 输入参数 String strText br
* 返回类型
*/
public String transferChinese(String strText) {
try {
strText = MimeUtility encodeText(new String(strText getBytes()
GB ) GB B );
} catch (Exception e) {
e printStackTrace();
}
return strText;
}
/**
* br
* 方法说明 往附件组合中添加附件 br
* 输入参数 br
* 返回类型
*/
public void attachfile(String fname) {
file addElement(fname);
}
/**
* br
* 方法说明 发送邮件 br
* 输入参数 br
* 返回类型 boolean 成功为true 反之为false
*/
public boolean sendMail() {
// 构造mail session
Properties props = new Properties() ;
props put( mail *** tp host host);
props put( mail *** tp auth true );
Session session = Session getDefaultInstance(props
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username password);
}
});
//Session session = Session getDefaultInstance(props);
//Session session = Session getDefaultInstance(props null);
try {
// 构造MimeMessage 并设定基本的值
MimeMessage msg = new MimeMessage(session);
//MimeMessage msg = new MimeMessage();
msg setFrom(new InternetAddress(from));
//msg addRecipients(Message RecipientType TO address); //这个只能是给一个人发送email
msg setRecipients(Message RecipientType BCC InternetAddress parse(to)) ;
subject = transferChinese(subject);
msg setSubject(subject);
// 构造Multipart
Multipart mp = new MimeMultipart();
// 向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent setContent(content text/;charset=gb );
// 向MimeMessage添加(Multipart代表正文)
mp addBodyPart(mbpContent);
// 向Multipart添加附件
Enumeration efile = file elements();
while (efile hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
filename = efile nextElement() toString();
FileDataSource fds = new FileDataSource(filename);
mbpFile setDataHandler(new DataHandler(fds));
mbpFile setFileName(fds getName());
// 向MimeMessage添加(Multipart代表附件)
mp addBodyPart(mbpFile);
}
file removeAllElements();
// 向Multipart添加MimeMessage
msg setContent(mp);
msg setSentDate(new Date());
msg saveChanges() ;
// 发送邮件
Transport transport = session getTransport( *** tp );
nnect(host username password);
transport sendMessage(msg msg getAllRecipients());
transport close();
} catch (Exception mex) {
mex printStackTrace();
//Exception ex = null;
//if ((ex = mex getNextException()) != null) {
//ex printStackTrace();
//}
return false;
}
return true;
}
/**
* br
* 方法说明 主方法 用于测试 br
* 输入参数 br
* 返回类型
*/
public static void main(String[] args) {
MailUtils sendmail = new MailUtils();
sendmail setHost( );
sendmail setUserName( se );
sendmail setPassWord( bric );
sendmail setTo( che );
sendmail setFrom( se );
sendmail setSubject( java代码发邮件和附件你好 这是测试! );
sendmail setContent( 你好这是一个带多附件的测试! );
// Mail sendmail = new
// Mail( du_jiang 你好 胃 你好吗java代码发邮件和附件? );

推荐阅读