我一直在阅读博客并尝试了大量实现,但仍未能将图像附加到我通过GMail使用java发送的电子邮件中。我下载了所有的罐子并添加了GMailSender.java,GMailAuthenticator.java和JSSEProvider.java,我能够定期发送常规电子邮件。我尝试过的方式如下所示,中间部分被注释为我希望添加图像的部分。下面是我尝试执行此操作时logcat上的输出。当然,我错过了一些非常简单的事情。有人能指出我吗?提前谢谢。
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
/*
// Create your new message part
BodyPart imgPart = new MimeBodyPart();
// Create a related multi-part to combine the parts
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(imgPart);
String fileName = "http://.../sampleBarcode.png";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
if (classLoader == null) {
System.out.println("IT IS NULL AGAIN!!!!");
}
}
DataSource ds = new URLDataSource(classLoader.getResource(fileName));
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "<logoimg_cid>");
multipart.addBodyPart(imgPart);
message.setContent(multipart);
*/
if(recipients.indexOf(',') > 0) {
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
}
else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}
catch(Exception e){Log.e("EMAIL_ERROR",e.getMessage(), e);}
}
null
java.lang.NullPointerException
at javax.activation.URLDataSource.getContentType(URLDataSource.java:91)
at javax.activation.DataHandler.getContentType(DataHandler.java:218)
...
...
(plus some more)
答案 0 :(得分:11)
我修改了函数以接受File参数并将其附加到电子邮件,这里是
public synchronized void sendMail(String subject, String body, String sender, String recipients, File attachment) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body);
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attachment);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
message.setContent(mp);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}