这是我的代码:
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(messageSubject);
message.setText(messageBody);
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageBody);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart );
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
即使邮件附件由于某种原因失败,我如何仍能发送电子邮件?ATM 如果附件失败,则不会发送电子邮件,这对我来说很糟糕。我应该使用另一个 try/catch 语句吗?最后我也应该使用吗?我是 Java 新手(3-4 周)
编辑:将我的代码更改为此,但没有工作
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(messageSubject);
message.setText(messageBody);
try {
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageBody);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
} catch (Exception e) {
message.setText(messageBody2);
e.printStackTrace();
}
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}