我试图用Java发送带附件的电子邮件。每次运行该文件时,我都会得到一个" java.lang.ExceptionInInitializerError。"附加的jar文件是' javax.mail'。 ..有谁知道为什么以及如何解决它?
public class JavaEmailAttach {
static Properties mailServerProperties;
static Session getMailSession;
static MimeMessage msg;
public static void main(String args[]) throws AddressException, MessagingException {
final String sourceEmail = "malikee4u@gmail.com"; // Gmail id
final String password = "xxxxxxxxx";
final String toEmail = "xxxxxx@yahoo.com"; //destination email id
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator authentication = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sourceEmail, password);
}
};
Session session = Session.getInstance(props, authentication);
generateAndSendEmail(
session,
toEmail,
"JavaMail API example with Image Attachment",
"Test email with attachment. Please find here attached Image.");
}
public static void generateAndSendEmail(Session session, String toEmail, String subject,
String body) {
try {
System.out.println("generateAndSendEmail() starts..");
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.addHeader("Content-type", "text/HTML; charset=UTF-8");
mimeMessage.addHeader("format", "flowed");
mimeMessage.addHeader("Content-Transfer-Encoding", "8bit");
mimeMessage.setFrom(new InternetAddress("malike4u@gmail.com",
"NoReply"));
mimeMessage.setReplyTo(InternetAddress.parse("malike4u@gmail.com", false));
mimeMessage.setSubject(subject, "UTF-8");
mimeMessage.setSentDate(new Date());
mimeMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail, false));
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "E:/Malik/PDF REPORT/images/RED.jpg";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<br><h3>Find below attached image</h3>"
+ "<img src='cid:image_id'>", "text/html");
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
System.out.println("Finally Send message..");
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}