![](/img/trans.png)
[英]I cannot send an Email using the Java Mail API the email is sent but is not received or displayed in the emails sent
[英]attaching pictures to an email being sent using java mail API
我有一個方法,我用來發送使用java的電子郵件。 我想知道如何將圖片附加到電子郵件的頂部? 我嘗試使用MimeMessageParts或其他東西,我無法讓它工作? 我希望能夠將BufferedImage作為參數傳遞給方法,並將其附加到頂部..任何幫助將不勝感激:)
public static void Send(final String username, final String password,
String recipientEmail, String ccEmail, String title, String message)
throws AddressException, MessagingException
{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@gmail.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
對於附件,您需要創建單獨的MimeBodyPart
,這是示例代碼,
MimeBodyPart attachmentPart = new MimeBodyPart(); FileDataSource fileDataSource = new FileDataSource(filename) { @Override public String getContentType() { return "application/octet-stream"; } }; attachmentPart.setDataHandler(new DataHandler(fileDataSource));
對於郵件文本,您需要另一個MimeBodyPart
MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(bodyText);
將這兩個MimeBodyPart
組合成Multipart
Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); multipart.addBodyPart(attachmentPart);
最后,發送電子郵件
........... final MimeMessage msg = new MimeMessage(session); msg.setContent(multipart); Transport.send(msg);
有關詳細信息,請參閱此鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.