Here is my code:
MimeMessage mail = new MimeMessage(session);
mail.setFrom(from);
MimeMultipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyText, "text/html");
multipart.addBodyPart(htmlPart);
MimeBodyPart imgPart=new MimeBodyPart();
String path = "/ivr/imagelogos/accenture.jpg";
DataSource ds=new FileDataSource(path);
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID","the-img-1");
multipart.addBodyPart(imgPart);
mail.setContent(multipart);
mail.setSentDate(new Date());
mail.setHeader("X-Mailer", "ALS Notifier Build 1.0.0.10");
// send the message
Transport.send(mail);
The code is being ran on a unix box - image path is based on unix file paths.
After running the code I receive this error:
IOException while sending message
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: /ivr/imagelogos/accenture.jpg (No such file or directory)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:676)
Sounds like the /ivr/imagelogos/accenture.jpg file doesn't exist. Are you sure that's the right path? Maybe it's supposed to be relative to some other path? If it does exist, does the user running the Java app have read permissions on it?
Img src= is the most efficient way to insert just a few images, otherwise you may find it useful/helpful to define an array for multiple images.
Related
I'm trying to figure it out of how to open an email using javax.mail. My goal is to provide a feature where a user clicks on a button and a default email will open with an attachment. So far, I'm using javax.mail and what it does is just sending the email right when the button is click. Is there a way to just open the email without direct sending? If so, how? I'm using Java 8.
I can't use the 'mailto:' because I need to attach a png file when a user opens an email. Also I'm not sure if I should use ProcessBuilder to open outlook because every user's machine will have a different userName within the C Drive or I'm not sure how to use that.
Here's my code just in case if you need it
String result;
String to = "....gov";
String from = "....gov";
String host = "....gov";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(emailFrom));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo));
message.setSubject("meh!");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("text body mehmehmehmeh");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "testing.png";
DataSource source = new FileDataSource(filename);
String imageString = toDataURL.substring("data:image/png;base64," .length());
byte[] contentdata = imageString.getBytes();
ByteArrayDataSource ds = new ByteArrayDataSource(contentdata, "image/png");
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart); //
// Send the complete message parts
message.setContent(multipart);
Transport.send(message);
result = "Sent message successfully....";
}catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
Is there a way to just open the email without direct sending? If so, how?
Don't call Transport.send. Then follow the steps in this answer. and start with msg.saveChanges(). There is an X-Unsent header in that answer that can be used to toggle some outlook features.
Also I'm not sure if I should use ProcessBuilder to open outlook because every user's machine will have a different userName within the C Drive or I'm not sure how to use that.
You use File.createTempFile​ as this will account for user names. If you need to save in a different location you can read from System.getProperty​ or if you are only targeting Windows machines you can read from System.getenv. To list all the environment vars you can type set in the command window.
I am trying to send email with image attachment from my JBOSS server. I am using eclipse Ide. Where should I put my image resource that is to be sent at email attachment.
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("Logo.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
msg.setContent(multipart);
// Send message
Transport.send(msg);
In the above code I am providing Logo.png, where should I put that file in the folder hierarchy.
The folder structure is:
project-backend
-DeployedResources
-src
--main
---java
----com
-----abc
------utils
-------EmailUtil.java -> File with the email sending logic
---resources
----META-INF
-----persistence.xml
---webapp
----WEB_INF
-----beans.xml
-----web.xml
I tried placing that file at multiple locations by everytime I am get the error in line:
// Send message
Transport.send(msg);
The error is:
java.lang.NullPointerException
javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:226)
javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:299)
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1375)
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1021)
javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:419)
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1354)
javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2107)
javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2075)
com.abc.utils.EmailUtil.sendEmail(EmailUtil.java:69)
javax.mail.Transport.send(Transport.java:123)
I was able to solve the problem by placing the resources in the bin folder of jboss server.
Here is the exception I get sometimes when trying to send mail with attachments on Appengine :
java.lang.NoClassDefFoundError: java.awt.Component is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.apphosting.runtime.security.shared.stub.java.awt.Component.<clinit>(Component.java)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:375)
at javax.activation.MailcapCommandMap.getDataContentHandler(MailcapCommandMap.java:588)
at javax.activation.MailcapCommandMap.createDataContentHandler(MailcapCommandMap.java:542)
at javax.activation.DataHandler.getDataContentHandler(DataHandler.java:617)
at javax.activation.DataHandler.getInputStream(DataHandler.java:240)
at javax.activation.DataHandlerDataSource.getInputStream(DataHandler.java:708)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:764)
at javax.mail.internet.MimeUtility.getEncoding(MimeUtility.java:718)
at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:548)
at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:133)
at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:1393)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:1366)
at javax.mail.Transport.send(Transport.java:76)
at javax.mail.Transport.send(Transport.java:48)
I use this code to send a mail :
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(mailSession);
MimeMultipart multipart = new MimeMultipart();
// first part (the html)
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlText, "text/html");
multipart.addBodyPart(htmlPart);
// second part (the image)
BodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setFileName("screenshot.jpg");
DataSource imageSrc = new ByteArrayDataSource(image, "image/jpeg");
attachmentPart.setDataHandler(new DataHandler(imageSrc));
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
message.saveChanges();
Transport.send(message);
When this exception occurs on an instance, it becomes unstable and is no longer able to send emails with attachment. The only solution I found is to kill the instance and start a new one.
Is "image" really a byte array?
The stack trace suggests that you've set the attachment as an Image object, so JAF is trying to find a DataContentHandler to convert it to a byte array, and that DataContentHandler is using an AWT class that's not allowed. There's no such DataCOntentHandler configured by default so I don't know where it's coming from. Maybe GAE has a different configuration?
Also, what version of JavaMail are you using?
I want to add an image to an email along with some text without having to attach the image in the email. Would this be possible ?
I have managed to do the following so far but it is sent with an attachment and also the image in the mail. I want it without an attachment but as a part of the mail
`Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailID));
message.setSubject("Password Reset");
Multipart multipart = new MimeMultipart("related");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>Hi<img src=\"cid:the-img-1\"/></body></html>", "text/html");
multipart.addBodyPart(htmlPart);
BodyPart imgPart=new MimeBodyPart();
// Loading the image
DataSource ds=new FileDataSource("C:\\Users\\XYZ\\Desktop\\images.jpg");
imgPart.setDataHandler(new DataHandler(ds));
//Setting the header
imgPart.setHeader("Content-ID","the-img-1");
multipart.addBodyPart(imgPart);
// attaching the multi-part to the message
message.setContent(multipart);
Transport.send(message);`
You need to construct a multipart/related message.
You will be need to construct an html based e-mail for that purpose.
There are plenty of examples that you can get on google for that.
One example is look at here.
Note that image you want to send should be accessible over http to recipient. May be you can upload it on google drive or some image server
i have using the following code for sending mail within a domain.
public void sendMail(String mailServer, String from, String to,
String subject, String messageBody, String[] attachments)
throws MessagingException, AddressException {
// Setup mail server
Properties props = System.getProperties();
props.put("mail.smtp.host", mailServer);
// Get a mail session
Session session = Session.getDefaultInstance(props, null);
// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);
// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();
// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);
// add any file attachments to the message
addAtachments(attachments, multipart);
// Put all message parts in the message
message.setContent(multipart);
// Send the message
Transport.send(message);
System.err.println("Message Send");
}
protected void addAtachments(String[] attachments, Multipart multipart)
throws MessagingException, AddressException {
for (int i = 0; i < attachments.length ; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// assume that the filename you want to send is the same as the
// actual file name - could alter this to remove the file path
attachmentBodyPart.setFileName(filename);
// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}
but if with the same code i try to send an email outside the domain, say i am sending email from mjsharma#domain.com to mhsharma#gmail,com then it fails and gives me the following error. 550 5.7.1 Rcpt command failed: Mail denied due to site's policy
Am i missing something in the above code.
Please help me
I suspect that's not a problem in your code, but in your mail server (sendmail?) configuration. I would talk to whoever administers your mail infrastructure.
It's likely that your local mail server requires you to authenticate before sending mail out into the world. This is a common policy to prevent spammers from relaying their mail through it.
Assuming your machine has Outlook installed... have you tried using moyosoft's java outlook connector? it's pretty simple to use and passes through network restrictions because it connects to your Outlook application and then sends the mail, so any restriction on smtp ports or servers/proxy policies will be ignored if your Outlook client is working fine.
if you are doing it with command line server-side then i guess this answer is useless for you.
Source: i had similar problem (not same error code, more like an intranet restriction) and using this library solved my problem because of the posted above.