Java コードで生成されたレポートを送信しようとしています。ジャスパー レポートを使用して、さまざまなレポートを生成しています。私のレポートでは、ヘッダーに画像があります。これは、HTML を除くレポートのすべての形式 (PDF、XLS、RTF) で正常に機能します。画像が見つからないため、HTML レポートに画像が表示されません。
電子メールで画像を送信し、Java Mail を使用して HTML レポートで使用するにはどうすればよいですか?
Java コードで生成されたレポートを送信しようとしています。ジャスパー レポートを使用して、さまざまなレポートを生成しています。私のレポートでは、ヘッダーに画像があります。これは、HTML を除くレポートのすべての形式 (PDF、XLS、RTF) で正常に機能します。画像が見つからないため、HTML レポートに画像が表示されません。
電子メールで画像を送信し、Java Mail を使用して HTML レポートで使用するにはどうすればよいですか?
以下は、添付ファイルなどを送信するために必要なすべてのもので、JavaMail クライアントを作成したときに大いに役立ちました: Send Email's Javaとこれ: Java Sending Embedded images in JavaMailと here Sending HTML Email with imagesは、あなたの方向性をより示しているようです。
相対 URL の代わりに絶対 URL (例: http://servername.com/images/xyz.jpg ) を使用できます。JasperReport は、絶対 URL を使用するように構成できます。
または
これが埋め込みメールで機能するかどうかはわかりません。ただし、インライン イメージを使用してみることができます。イメージを base64 文字列に変換する必要があります。画像が大きすぎて画像が変更されたときに維持するのが難しい場合、これにより HTML のサイズが大きくなります。
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/ /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" width="16" height="14" alt="embedded folder icon">
img はドキュメント内に保存されるため、PDF、XLS、RTF で動作します。
HTML ではそれができず、参照する必要があります。src プロパティを使用して img を作成し、その img をメールの添付ファイルとして含めて、読み取れるようにします。
また
Web サーバーから http を介して画像にアクセスできるようにし、src=http://myimgserver.com/myimg.jpg をポイントします。
JavaMail を使用して、画像と添付ファイルが埋め込まれた HTML メールを送信します。(私の最後の投稿はリンク ( https://github.com/QuickrWorld/email-sender.git ) だったので削除されました。その点は有効だと思います。git リポジトリが削除または変更されて、もはや有効な答えではありませんでしたか?)。そのため、以下の応答にコードを直接追加しました。とはいえ、なぜ私の答えが削除対象に選ばれたのか、まだ疑問に思っています。この投稿の他の回答も単なるリンクです。それとも何か足りない?)
// EmailSender.java
package com.quickrworld.mail;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailSender {
static Properties p = null;
static Properties getDefaultProperties() {
if (p == null) {
p = new Properties();
String mailSmtpHost = "smtp.gmail.com";
String mailSmtpAuth = "true";
String mailSmtpPort = "465";
String mailSmtpSocketFactoryPort = "465";
String mailSmtpSocketFactoryClass = "javax.net.ssl.SSLSocketFactory";
String mailSmtpSocketFactoryFallback = "false";
String mailDebug = "false";
p.put("mail.smtp.host", mailSmtpHost);
p.put("mail.smtp.auth", mailSmtpAuth);
p.put("mail.smtp.port", mailSmtpPort);
p.put("mail.smtp.socketFactory.port", mailSmtpSocketFactoryPort);
p.put("mail.smtp.socketFactory.class", mailSmtpSocketFactoryClass);
p.put("mail.smtp.socketFactory.fallback",
mailSmtpSocketFactoryFallback);
// p.put("mail.smtp.starttls.enable","true");
// p.put("mail.smtp.EnableSSL.enable","true");
p.put("mail.debug", mailDebug);
}
return p;
}
public void sendMessage(
String mailSubject,
String mailFrom,
List<String> mailTos,
List<String> mailCcs,
List<String> mailBccs,
String html,
List<ImageResource> images,
List<Resource> attachments,
Properties p,
String user,
String password) throws MessagingException, MalformedURLException {
Session s = Session.getInstance(p);
Message m = new MimeMessage(s);
m.setSubject(mailSubject);
InternetAddress from = new InternetAddress(mailFrom);
for (String mailTo : mailTos) {
InternetAddress to = new InternetAddress(mailTo);
m.addRecipient(Message.RecipientType.TO, to);
}
for (String mailCc : mailCcs) {
InternetAddress cc = new InternetAddress(mailCc);
m.addRecipient(Message.RecipientType.CC, cc);
}
for (String mailBcc : mailBccs) {
InternetAddress bcc = new InternetAddress(mailBcc);
m.addRecipient(Message.RecipientType.BCC, bcc);
}
m.setFrom(from);
Multipart multipart = new MimeMultipart("related");
// html
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");
multipart.addBodyPart(htmlPart);
// images
for (ImageResource imageResource : images) {
String path = imageResource.getPath();
String fileName = imageResource.getName();
String cid = imageResource.getCid();
boolean isURL = imageResource.isURL();
addImageWithCid(multipart, path, fileName, cid, isURL);
}
// attachments
for (Resource attachment : attachments) {
addAttachment(multipart, attachment);
}
// message
m.setContent(multipart);
// send
Transport transport = s.getTransport("smtp");
transport.connect(user, password);
transport.sendMessage(m, m.getAllRecipients()); // Actually this can be any valid address set
transport.close();
}
private void addAttachment(Multipart multipart,
Resource attachment) throws MessagingException, MalformedURLException {
String attachmentPath = attachment.getPath();
String attachmentName = attachment.getName();
boolean isURL = attachment.isURL();
if(isURL) {
BodyPart attachmentBodyPart = new MimeBodyPart();
URL attachmentURL = new URL(attachmentPath);
URLDataSource source = new URLDataSource(attachmentURL);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(attachmentName);
multipart.addBodyPart(attachmentBodyPart);
} else {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(attachmentName);
multipart.addBodyPart(attachmentBodyPart);
}
}
private void addImageWithCid(
Multipart multipart,
String imageFilePath,
String imageFileName,
String imageFileCid,
boolean isURL) throws MessagingException, MalformedURLException {
if(isURL) {
BodyPart imgPart = new MimeBodyPart();
URL imageFileURL = new URL(imageFilePath);
URLDataSource ds = new URLDataSource(imageFileURL);
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", imageFileCid);
imgPart.setFileName(imageFileName);
multipart.addBodyPart(imgPart);
} else {
BodyPart imgPart = new MimeBodyPart();
DataSource ds = new FileDataSource(imageFilePath);
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", imageFileCid);
imgPart.setFileName(imageFileName);
multipart.addBodyPart(imgPart);
}
}
}
// Resource.java
package com.quickrworld.mail;
public class Resource {
private String path;
private String name;
private boolean isURL;
public Resource() {
}
public Resource(String path, boolean isURL) {
this(path, path, isURL);
}
public Resource(String path, String name, boolean isURL) {
this.path = path;
this.name = name;
this.isURL = isURL;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isURL() {
return isURL;
}
public void setURL(boolean isURL) {
this.isURL = isURL;
}
}
// ImageResource.java
package com.quickrworld.mail;
public class ImageResource extends Resource {
private String cid;
public ImageResource() {
super();
}
public ImageResource(String path, String name, String cid, boolean isURL) {
super(path, name, isURL);
this.cid = cid;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
}
// EmailMain.java
package com.quickrworld.mail;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.MessagingException;
public class EmailMain {
// Please ensure you have a tomcat running on port 8080 on localhost (for tomcat.png and favicon.ico)
// please ensure you have files file1.txt and file2.txt in the working directory (for attachments)
public static void main(String[] args) {
EmailSender emailSender = new EmailSender();
String mailSubject = "My Mail Subject (Named)";
String mailFrom = "from@mailfrom.com";
List<String> mailTos = new ArrayList<String>();
mailTos.add("mailto@maito.com");
List<String> mailCcs = new ArrayList<String>();
mailCcs.add("mailcccs@mailccs.com");
List<String> mailBccs = new ArrayList<String>();
mailBccs.add("mailbccs.mailbccs@mailbccs.com");
String html = "<html><body><h2>Heading</h2>Our logo:<br/>"
+ "<img src=\"cid:img-cid-1\"/><br/>See images in the email - and two attachments<br/>"
+ "<div><img src=\"cid:img-cid-2\"/></div></body></html>";
// remove the values for user and password before posting to git
String user = "x@y.com";
String password = "password";
Properties p = EmailSender.getDefaultProperties();
p.put("mail.debug", "true");
List<ImageResource> imageResources = new ArrayList<ImageResource>();
imageResources.add(new ImageResource("logo.png","logo.png","<img-cid-1>",false));
imageResources.add(new ImageResource("http://localhost:8080/favicon.ico","favicon.ico","<img-cid-2>",true));
List<Resource> attachmentResources = new ArrayList<Resource>();
attachmentResources.add(new Resource("file1.txt", "attached-file1.txt", false));
attachmentResources.add(new Resource("file2.txt", "attached-file2.txt", false));
attachmentResources.add(new Resource("http://localhost:8080/tomcat.gif","attached-tomcat.gif",true));
try {
emailSender.sendMessage(mailSubject, mailFrom, mailTos, mailCcs,
mailBccs, html, imageResources,
attachmentResources, p, user, password);
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}