在我的应用程序中,我使用 smtp 发送邮件。我想将图像文件附加到邮件。我如何附加它?我尝试过。但没有在邮件中获取图像。它给出了小图标。 请帮忙。提前致谢。 下面是邮件代码和邮件图像 -
public class MailImageFile extends javax.mail.Authenticator {
public MailImageFile(){
}
public void Mail(String user, String pass) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(USERNAME));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(TO));
message.setSubject("Testing Subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/wallpaper.jpg"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("image.png");
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
messageBodyPart.setHeader("Content-ID","<vogue>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
最佳答案
再考虑一下:
使用javax.mail.util.ByteArrayDataSource:
Multipart multipart = new MimeMultipart();
DataSource source = new ByteArrayDataSource(imageFile, "image/bmp");
// creates body part for the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Hi...", "text/html; charset=utf-8");
MimeBodyPart attachPart;
attachPart = new MimeBodyPart();
attachPart .setDataHandler(new DataHandler(source));
attachPart .setFileName(filename);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);
message.setContent(multipart);
ByteArrayDataSource的构造函数需要字节数组或 InputStream 作为参数。因此,如果您的位图位于变量 bmp 中,则可以将其获取到 byteArray,如下所示:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
并在 ByteArrayDataSource 中使用它,如下所示:
DataSource source = new ByteArrayDataSource(byteArray, "image/png");
关于android - 在android中使用smtp附加文件并发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15548246/