Javamail一个非常之怪的问题!不信你去试!
我在测试会用Javamail传送附件的问题,
在传送的附件除了是.txt的附件全部都符合了我的要求,
就是在传送.txt附件的时候,
信的内容和.txt附件的内容正好调转头了!
你说怪不?
把这个.txt后缀我手动改为.doc或者.dat也可以成功传送附件,怪怪!
源代码如下:
===========================================================================================
private static String sendAaccessoriesMail()
{
String fromAddr = "fromtest@126.com";
String toAddr = "totest@126.com";
String fileName = "c:/cdnlog.txt";
String colorContent = "测试html邮件的内容:<font color=red><b>红红的,粗粗的哦</b></font>";
Properties prop = System.getProperties();
prop.put("mai.smtp.host", "smtp.126.com");
prop.put("mail.smtp.auth", String.valueOf(auth));
if (sessionDebug)
{
prop.put("mail.debug", String.valueOf(sessionDebug));
}
Session mail_session = Session.getInstance(prop, null);
mail_session.setDebug(sessionDebug);
try
{
Message msg = new MimeMessage(mail_session);
msg.setFrom(new InternetAddress(fromAddr));
address = InternetAddress.parse(toAddr);
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("测试html邮件主题");
msg.setSentDate(new Date());
/* Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
String colorContent = "测试html邮件的内容:<font color=red><b>红红的,粗粗的哦</b></font>";
mbp.setContent(colorContent,"text/html;charset=GB2312");
mp.addBodyPart(mbp);
msg.setContent(mp);
*/
if(null!=fileName&!fileName.equalsIgnoreCase(""))
{
File file = new File(fileName);
MimeBodyPart mbp1 = new MimeBodyPart();
//设定邮件的内容及类型
mbp1.setContent(colorContent,"text/html;charset=GB2312");
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileName);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(MimeUtility.encodeText(fds.getName(),"GB2312","B"));
System.out.println(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
}else
{
//若没有附件,就直接存邮件内容
msg.setContent(colorContent,"text/html;charset=GB2312");
}
//msg.setText("测试html邮件的内容:<font color=red><b>红红的,粗粗的哦</b></font>");
msg.saveChanges();
Transport transport = mail_session.getTransport("smtp");
if (auth)
{
transport.connect("smtp.126.com","fromtest","password");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}else
{
Transport.send(msg);
}
return ("发送至: " + toAddr + " 信件成功!");
} catch (Exception ex)
{
//System.out.println("发送到" + "test@126.com" + "邮件的时候发生错误!:");
ex.printStackTrace();
//返回所发送信箱失败的信息
return ("发送到:" + toAddr + " 信件发送失败!" + "\n");
}
}
===========================================================================================