用javamail发附件可以成功,但之前设置的msg.setText("")就没有用了,那不是就没有正文了吗,请问怎样解决这个问题呢,下面是原代码public class MailTest {
public static void main(String[] args) {
MailTest m = new MailTest();
m.send("smtp.163.com", "[email protected]", "[email protected]",
"这是一个测试邮件", "看到邮件就ok");
} public static void send(String smtpServer, String to, String from,
String subject, String body) {
try {
Properties props = new Properties();
AuthenticatorUtil author = new AuthenticatorUtil("fengweimsf", "***");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, author);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
false));
msg.setSubject(subject);
msg.setText(body);
msg.setSentDate(new Date());
Transport trans = session.getTransport("smtp"); //添加附件
//后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart();
MimeBodyPart mbp=new MimeBodyPart();
mbp.setText("hi");
mp.addBodyPart(mbp);
FileDataSource fds=new FileDataSource("d:\\2004321143908.rar");
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
msg.setContent(mp);
msg.saveChanges();
trans.send(msg, msg.getAllRecipients());
trans.close();
//Transport.send(msg);
System.out.println("send ok");
} catch(AddressException e) {
e.printStackTrace();
} catch(MessagingException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MailTest m = new MailTest();
m.send("smtp.163.com", "[email protected]", "[email protected]",
"这是一个测试邮件", "看到邮件就ok");
} public static void send(String smtpServer, String to, String from,
String subject, String body) {
try {
Properties props = new Properties();
AuthenticatorUtil author = new AuthenticatorUtil("fengweimsf", "***");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, author);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
false));
msg.setSubject(subject);
msg.setText(body);
msg.setSentDate(new Date());
Transport trans = session.getTransport("smtp"); //添加附件
//后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart();
MimeBodyPart mbp=new MimeBodyPart();
mbp.setText("hi");
mp.addBodyPart(mbp);
FileDataSource fds=new FileDataSource("d:\\2004321143908.rar");
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
msg.setContent(mp);
msg.saveChanges();
trans.send(msg, msg.getAllRecipients());
trans.close();
//Transport.send(msg);
System.out.println("send ok");
} catch(AddressException e) {
e.printStackTrace();
} catch(MessagingException e) {
e.printStackTrace();
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货