日期:2014-05-17  浏览次数:20743 次

javamail 附件和文本内容不能实现同时发送[在线等]
Properties props = System.getProperties();
props.put("mail.smtp.host", this.smtp);
props.put("mail.smtp.auth", "true");

SendMailAuthenticator myauth = new SendMailAuthenticator();
myauth.check(this.user, this.password);
Session session = Session.getDefaultInstance(props, myauth);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(this.from));//发信人

String[] to = this.addressee.split(";");//以;分割

if(to != null && to.length > 0)//收信人
{
int count = to.length;
InternetAddress[] address = new InternetAddress[count];
for(int i = 0; i < count; i++)
{
address[i] = new InternetAddress(to[i].toString());
System.out.println("收件人: "+to[i].toString());
}
msg.addRecipients(Message.RecipientType.BCC, address);
}

msg.setSentDate(new Date());//日期
msg.setSubject(subject, "UTF-8");//主题
msg.setContent(body, "text/html;charset=UTF-8");//内容

if(arrFileName != null && arrFileName.length > 0)//附件
{
try{
Multipart mp = new MimeMultipart();

int fileCount = this.arrFileName.length;//附件的个数
if(fileCount > 0)
{
String path = "";
for(int i = 0; i < fileCount; i++) {
MimeBodyPart mbp = new MimeBodyPart();
path = arrFileName[i];
System.out.println("附件地址: "+arrFileName[i]);
FileDataSource fds = new FileDataSource(path);
mbp.setDataHandler(new DataHandler(fds));
try {
mbp.setFileName(MimeUtility.encodeText(fds.getName(),"gb2312",null));
} catch (UnsupportedEncodingException e) {
this.setErrorInfo("文件名不能是中文字符");
e.printStackTrace();
}
mp.addBodyPart(mbp);// 添加至Multipart
}
msg.setContent(mp);// Multipart加入到信件
}

}catch(MessagingException e){
System.out.println("添加附件出错:"+e.getMessage());
}
}else{
System.out.println("-------没有附加附件-------");
}

msg.saveChanges();

Transport transport = session.getTransport("smtp");
transport.connect(this.smtp, this.user, this.password);
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.BCC));
transport.close();



------------------------------------------
代码有些乱~
主要看红色的两处,第一个是设置文本内容,第二个是添加附件的。
为什么添加附件的这个在最后,发出去的邮件里就只有附件;
把第一个调在最后,发出去的邮件里就只有文本内容;
是不是不能这样写?
怎样实现同时成功发送附件和文本内容呢?

------解决方案--------------------
不会,但是在网上有一段,你看一下,或许对你有帮助
Java code
package com.sendEmailTest.bak;
  
import java.io.ByteArrayInputStream;   
import java.io.ByteArrayOutputStream;   
import java.io.FileInputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.OutputStream;   
import java.util.Arrays;   
import java.util.Date;   
import java.util.Properties;   
  
import javax.activation.DataHandler;   
import javax.activation.DataSource;   
import javax.activation.FileDataSource;   
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.