send an attachment in email with java - java

I'm writing a java method to send email with an attachment.
I want to attach the file in target/results folder to the email. I'm unable to attach the email
Following is what i have so far:
public static void sendEmail() {
String to = "xyz#xyz.com";
String from = to;
String host = "mail.xyz.com";
String linkToLatestTest = getLink();
// Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
// compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Test results from today");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart
.setText("Hello,\nThis is an email regarding latest test");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "target/results";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
Here is the error that i got:
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: target\results (Access is denied)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.performanceTestLink.PerformanceTestLink.sendEmail
(PerformanceTestLink.java:49)
at com.performanceTestLink.PerformanceTestLink.main
(PerformanceTestLink.java:12)
Caused by: java.io.FileNotFoundException: target\results (Access is
denied)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at javax.activation.FileDataSource.getInputStream(FileDataSource.java:97)
at javax.activation.DataHandler.writeTo(DataHandler.java:305)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1485)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:865)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:462)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:103)
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:889)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1485)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1773)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1119)
... 4 more
Any leads on this would be helpful.
Thanks in advance.

target\results looks like a directory as a target and you are trying to create a file named result without extension within that directory.
Better you can do as follows
messageBodyPart = new MimeBodyPart();
String filename = "/home/user/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
And make sure that the directory where the file is located has proper access

Related

Not able to send a zip file through javamail

I am trying to send an attachment containing a zip file through javamail. However, while sending it throws an exception as
com.sun.mail.smtp.SMTPSendFailedException: 552-5.7.0 This message was blocked because its content presents a potential 552-5.7.0 security issue.
I added MIME content type as application/zip but facing
javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type
application/zip at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
Below is my code snippet:
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "application/zip");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
File srcFile = new File(System.getProperty("user.dir")+ "/Reports/");
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(srcFile.getPath()+"/Report.zip");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("Report.zip");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
When I remove the .zip extension it works fine but not with .zip.
Your code is adding the attachment twice, which I'm sure is not what you want. Replace your code with this:
MimeBodyPart messageBodyPart = new MimeBodyPart();
String srcFile = System.getProperty("user.dir") + "/Reports/Report.zip";
messageBodyPart.attachFile(srcFile, "application/zip", "base64");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);

getting syntax error in property.setProperty("mail.smtp.host",host);

I am getting the syntax for the below line while trying to send the mail through SMTP .I tried in google but didnt get any relevant answer.
property.setProperty("mail.smtp.host",host);
CODE:
public class SendMail {
//Recipient Mail id
String to = "Receiver Mail ID";
//Sender Mail Id
String from = "Sender Mail ID";
//Sending email from the localhost
String host = "localhost";
//Get System Properties
Properties property = System.getProperties();
//Setup the mail server
property.setProperty("mail.smtp.host",host);
property.setProperty("mail.smtp.port" , "465");
//property.put("mail.smtp.auth", "true");
//Get the default session object
Session session = Session.getDefaultInstance(property);
try
{
//Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
//Set From: header field of the header
message.setFrom(new InternetAddress(from));
//Set To : header field of the header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set Subject : header field
message.setSubject("Automation Testing Report");
//Create the Message part
BodyPart messageBodypart = new MimeBodyPart();
//Enter the message in the Mail Body
messageBodypart.setText("***********Find the below for the Report****************");
//Create a Multipart Message
Multipart multipart = new MimeMultipart();
//Set Text message part
multipart.addBodyPart(messageBodypart);
//Part two is attachment
/*create the Message part*/
messageBodypart = new MimeBodyPart();
String filename = "E:\\Project\\jar\\Selenium Scripts\\Hybrid_Driven\\test-output\\emailable-report.html";
DataSource source = new FileDataSource(filename);
messageBodypart.setDataHandler(new DataHandler(source));
messageBodypart.setFileName(filename);
//set the text message part
multipart.addBodyPart(messageBodypart);
//Send the complete message part
message.setContent(multipart);
//Send message
Transport.send(message);
System.out.println("Mail has sent successfully");
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}
Please help me to resolve this issue.
You cannot put java code directly into a class. It needs to be within methods. The following is happily accepted by the compiler:
public class SendMail {
...
//Get System Properties
java.util.Properties property = System.getProperties();
void doSomething()
{
property.setProperty("mail.smtp.host", host);
property.setProperty("mail.smtp.port", "465");
...
}
}

Error when sending Mail and attachment in Java

I have a function to send mail with attachment in java. It works when i uploaded the attachment. However, the problem is that if i have to send a mail without attachment, it says error when i send a mail and i did not upload any attachment.
here is my code:
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String html = text;
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abdool.latiff#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(html, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
any idea how i can solve this?
i get this error:
org.apache.jasper.JasperException: java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: C:\Users\gro\Desktop (Access is denied)
Its just not able to find the file..
I am not sure where you are getting the attachment field set.
But, wrapping the fragment of code that is attaching the file to message, something like this below should work for you:
if(attachment != null && attachment.length() > 0) {
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
I don't quite understand your implementation as the filename is set within the code without any user interaction. I suggest you change the body a little bit to get something like:
if(filename!=null) {
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
Let me see if I understand, you get this when you try to sent an email without attachment??
So the variable "attachment" is null??
So you are trying to load the file "C:/Users/gro/Desktop/null"??
And you are get a FileNotFoundException for that?? -.-
Without seeing what "attachment" is, it is going to be hard to figure out what you are doing. As others have already mentioned above, you need to check the value of "attachment" and if it exists (non-null or File.exists()) then the block of code for attaching the file to email should be executed.
Can you please hardcode the file path (including file name) and try the operation, I think your 'attachement' is either getting set to null or some non existing directory.

How to attach a PDF in a mail using Java Mail?

public static String sendMail(
String destino,
String texto,
String asunto,
byte[] formulario,
String nombre) {
Properties properties = new Properties();
try{
Session session = Session.getInstance(properties);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("reminder#companyname.com.ar"));
//Cargo el destino
if(destino!= null && destino.length > 0 && destino[0].length() > 0 ){
for (int i = 0; i < destino.length; i++) {
message.addRecipient(Message.RecipientType.TO,new InternetAddress(destino[i]));
}
}
//message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(asunto);
//I load the text and replace all the '&' for 'Enters' and the '#' for tabs
message.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));
Transport.send(message);
return "Mensaje enviado con éxito";
}catch(Exception mex){
return mex.toString();
}
}
Hello everyone.
I was trying to figure out how can I attach the PDF sent by parameters as formulario in the code previously shown.
The company used to do the following trick for this matter but they need to change it for the one previously shown:
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(
texto.replaceAll("&", "\n").replaceAll("#", "\t"));
//msg.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(
new DataHandler(
(DataSource) new InputStreamDataSource(formulario,
"EDD",
"application/pdf")));
messageBodyPart.setFileName(nombre + ".pdf");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(
"smtp.gmail.com",
"reminder#companyname.com.ar",
"companypassword");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return "Mensaje enviado con éxito";
} catch (Exception mex) {
return mex.toString();
Since you already can send emails, the adjust your code and add the following part to your code
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/home/file.pdf";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
original code taken from here
Is formulario a byte array in both cases? If so, just rewrite the first block of code to construct the message using the technique in the second block of code. Or replace InputStreamDataSource with ByteArrayDataSource in the new version.
The sending email with attachment is similar to sending email but here the additional functionality is with message sending a file or document by making use of MimeBodyPart, BodyPart classes.
The process for sending mail with attachment involves session object, MimeBody, MultiPart objects. Here the MimeBody is used to set the text message and it is carried by MultiPart object. Because of MultiPart object here sending attachment.
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Please find the attachment below");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "D:/test.PDF";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Email Sent Successfully !!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

how to attach generated pdf file mail in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Some body please tell me about how to attach available pdf file to mail.
I am use mail.jar and activation.jar for sending a mail.
I can send mail but I dont know how to send pdf file with attachment.
so please suggest me about that
thank you.
I just try
String filename = "file.pdf";
Multipart multipart1 = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart1.addBodyPart(messageBodyPart);
But still it not get data, it empty attached.
Send E-Mail with Attachment using JavaMail :
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendAttachment
{
public static void main(String [] args)
{
String to="ABC#gmail.com";//change accordingly
final String user="ABC#XYZ.com";//change accordingly
final String password="xxxxx";//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password); } });
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Aleart");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "SendAttachment.java";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
source: http://www.javatpoint.com/example-of-sending-attachment-with-email-using-java-mail-api
Try this:
String SMTP_HOST_NAME = "mail.domain.com";
String SMTP_PORT = "111";
String SMTP_FROM_ADDRESS="xxx#domain.com";
String SMTP_TO_ADDRESS="yyy#domain.com";
String subject="Textmsg";
String fileAttachment = "C:\\filename.pdf";
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT );
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{protected javax.mail.PasswordAuthentication
getPasswordAuthentication()
{return new javax.mail.PasswordAuthentication("xxxx#domain.com","password");}});
try{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SMTP_FROM_ADDRESS));
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Test mail one");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SMTP_TO_ADDRESS));
msg.setSubject(subject);
// msg.setContent(content, "text/plain");
Transport.send(msg);
System.out.println("success....................................");
}
catch(Exception e){
e.printStackTrace();
}
Source: http://www.coderanch.com/t/586537/java/java/sample-code-java-mail-api
You should create MimeMultipart, MimeBodyPart, FileDataSource and DataHandler as follows:
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String filePath = "<file system path>";
String fileName = "display name"
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
Now, On MimeMessage use setContent method.

Categories