My below Java class has to copy a text file content and mail to recipients, along with a attached xls file,using java mail.
Now I can read and Mail the text file content but unable to attach the xls file.
Below are my snippet:
static void sendmail() throws IOException,
MessagingException,AddressException,FileNotFoundException
{
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy
HH:mm:ss");
Calendar cal = Calendar.getInstance();
String to1=getOrderinfo.to1;
String to2 = getOrderinfo.to2;
String to3 = getOrderinfo.to3;
String to4 = getOrderinfo.to4;
String from =getOrderinfo.from;
String host = getOrderinfo.host;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
String pathLogFile = "E:/car_failed_report/log.txt";
try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new
InternetAddress(to1));
message.setSubject(" CAR NOT YET INTEGRATED REPORT at
: "+dateFormat.format(cal.getTime()));
StringBuffer sb = new StringBuffer();
FileInputStream fstream = new
FileInputStream(pathLogFile);
BufferedReader br = new BufferedReader(new
InputStreamReader(fstream));
String singleLine;
while ((singleLine = br.readLine()) != null)
{
sb.append(singleLine + "<br>");
// CarParser1.sb1.append(singleLine +"<br>");
}
br.close();
String allLines;
allLines = sb.toString();
String allLines_html=" <html><head><title></title>
</head>"
+ "<body >"+allLines+"</body ></html>";
message.setContent(allLines_html, "text/html;
charset=ISO-8859-1");
MimeBodyPart attachPart = new MimeBodyPart();
File attachement = new File("E:\\car_failed_report
\\failed.xls");
if (attachement.exists()) {
attachPart.attachFile(attachement);
} else {
System.out.println("ERROR READING THE FILE");
throw new FileNotFoundException();
}
Transport.send(message);
System.out.println("Email Sent successfully....");
System.out.println();
}
catch(FileNotFoundException f1)
{
System.out.println("File not yet created..this is from
mailer class");
return;
}
catch (MessagingException mex)
{
System.out.println("Invalid Email Address.please provide
a valid email id to send with");
mex.printStackTrace();
}
Can any one Help me to attach the xls file.?
Thanks in advance.
You created the body part with the attachment but didn't add it to the message. Replace your code starting with message.setContent:
MimeMultipart mp = new MimeMultipart();
MimeBodyPart body = new MimeBodyPart();
body.setText(allLines_html, "iso-8859-1", "html");
mp.addBodyPart(body);
MimeBodyPart attachPart = new MimeBodyPart();
File attachement = new File("E:\\car_failed_report\\failed.xls");
if (attachement.exists()) {
attachPart.attachFile(attachement);
mp.addBodyPart(attachPart);
} else {
System.out.println("ERROR READING THE FILE");
throw new FileNotFoundException();
}
message.setContent(mp);
Related
I am trying to send email with created pdf document as the attachment, the environment i am working is the REST based java spring boot application,
Actually i know how to send email with the thymeleaf template engine, but how can i create a pdf document in memory, and send it as a attachment, this is the code that i am using for sending email.
Context cxt = new Context();
cxt.setVariable("doctorFullName", doctorFullName);
String message = templateEngine.process(mailTemplate, cxt);
emailService.sendMail(MAIL_FROM, TO_EMAIL,"Subject", "message");
and this this the sendmail() function
#Override
public void sendPdfMail(String fromEmail, String recipientMailId, String subject, String body) {
logger.info("--in the function of sendMail");
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
try {
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject(subject);
message.setFrom(fromEmail);
message.setTo(recipientMailId);
message.setText(body, true);
FileSystemResource file = new FileSystemResource("C:\\xampp\\htdocs\\project-name\\logs\\health360-logging.log");
message.addAttachment(file.getFilename(), file);
this.mailSender.send(mimeMessage);
logger.info("--Mail Sent Successfully");
} catch (MessagingException e) {
logger.info("--Mail Sent failed ---> " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
Actually i need to create a kind of report with 2-3 pages as pdf file, and send in mail.
Also i need to send multiple pdf reports, in the mail, how can i do this, can you friends help me on this, i found something called jasper, is it something related to my environment,
This is how you can send a mail:
public void email() {
String smtpHost = "yourhost.com"; //replace this with a valid host
int smtpPort = 587; //replace this with a valid port
String sender = "sender#yourhost.com"; //replace this with a valid sender email address
String recipient = "recipient#anotherhost.com"; //replace this with a valid recipient email address
String content = "dummy content"; //this will be the text of the email
String subject = "dummy subject"; //this will be the subject of the email
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", smtpPort);
Session session = Session.getDefaultInstance(properties, null);
ByteArrayOutputStream outputStream = null;
try {
//construct the text body part
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(content);
//now write the PDF content to the output stream
outputStream = new ByteArrayOutputStream();
writePdf(outputStream);
byte[] bytes = outputStream.toByteArray();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
pdfBodyPart.setFileName("test.pdf");
//construct the mime multi part
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(textBodyPart);
mimeMultipart.addBodyPart(pdfBodyPart);
//create the sender/recipient addresses
InternetAddress iaSender = new InternetAddress(sender);
InternetAddress iaRecipient = new InternetAddress(recipient);
//construct the mime message
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSender(iaSender);
mimeMessage.setSubject(subject);
mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
mimeMessage.setContent(mimeMultipart);
//send off the email
Transport.send(mimeMessage);
System.out.println("sent from " + sender +
", to " + recipient +
"; server = " + smtpHost + ", port = " + smtpPort);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
//clean off
if(null != outputStream) {
try { outputStream.close(); outputStream = null; }
catch(Exception ex) { }
}
}
}
You can see that we create a MimeBodyPart with a DataSource created from bytes that resulted from a method named writePdf():
public void writePdf(OutputStream outputStream) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
Paragraph paragraph = new Paragraph();
paragraph.add(new Chunk("hello!"));
document.add(paragraph);
document.close();
}
Since we use a ByteOutputStream instead of a FileOutputStream no file is written to disk.
I would like to create a MimeMessage which must have two parts as shown below picture (Part_0 and Part_2)
I'm trying to use below code to generated s/mime
public static void main(String[] a) throws Exception {
// create some properties and get the default Session
Properties props = new Properties();
// props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
// session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
try {
msg.addHeader("Content-Type", "multipart/signed; protocol=\"application/pkcs7-signature;");
msg.setFrom(new InternetAddress(FROM_EMAIL));
InternetAddress[] address = {new InternetAddress(
TO_EMAIL)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test Subject");
msg.setSentDate(new Date());
// create and fill the first message part
MimeBodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setHeader("Content-Type", "text/html; charset=utf-8");
bodyPart1.setContent("<b>Hello World</b>", "text/html");
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(bodyPart1, 0);
try (OutputStream str = Files.newOutputStream(Paths
.get(UNSIGNED_MIME))) {
bodyPart1.writeTo(str);
}
signMime();
MimeBodyPart attachPart = new MimeBodyPart();
String filename = SIGNED_VALUE;
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName("smime.p7s");
attachPart.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s;");
attachPart.addHeader("Content-Transfer-Encoding", "base64");
attachPart.addHeader("Content-Description", "S/MIME Cryptographic Signature");
multiPart.addBodyPart(attachPart);
msg.setContent(multiPart, "multipart/signed; protocol=\"application/pkcs7-signature\"; ");
msg.saveChanges();
try (OutputStream str = Files.newOutputStream(Paths
.get(SIGNED_MIME))) {
msg.writeTo(str);
}
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
I used two MimeBodyPart however I always got one Part_0 and generated eml file shown below.
I haven't tried to compile it, but what you want is something like this. The inner multipart is a body part of the outer multipart.
msg.setFrom(new InternetAddress(FROM_EMAIL));
InternetAddress[] address = {new InternetAddress(
TO_EMAIL)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test Subject");
msg.setSentDate(new Date());
MultipartSigned multiSigned = new MultipartSigned();
// create and fill the first message part
MimeBodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setText("<b>Hello World</b>", "utf-8", "html");
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(bodyPart1);
// add other content to the inner multipart here
MimeBodyPart body = new MimeBodyPart();
body.setContent(multiPart);
multiSigned.addBodyPart(body);
try (OutputStream str = Files.newOutputStream(Paths
.get(UNSIGNED_MIME))) {
body.writeTo(str);
}
signMime();
MimeBodyPart attachPart = new MimeBodyPart();
String filename = SIGNED_VALUE;
attachPart.attachFile(filename,
"application/pkcs7-signature; name=smime.p7s", "base64");
attachPart.setFileName("smime.p7s");
attachPart.addHeader("Content-Description",
"S/MIME Cryptographic Signature");
multiSigned.addBodyPart(attachPart);
msg.setContent(multiSigned);
msg.saveChanges();
And you'll need this:
public class MultipartSigned extends MimeMultipart {
public MultipartSigned() {
super("signed");
ContentType ct = new ContentType(contentType);
ct.setParameter("protocol", "application/pkcs7-signature");
contentType = ct.toString();
}
}
You could make this much cleaner by moving more of the functionality into the MultipartSigned class.
What you are looking for is Spring Mime Helper.
I am able to use Apache POI to create a password protected .xls file successfully. However, when I use JavaMail to send it as an attachment, the file I receive in the recipient email address is no longer password protected. Does anyone know why this may be happening?
final String fname = "sample.xls";
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
POIFSFileSystem poiFileSystem = null;
FileOutputStream fileOut = null;
try {
fileInput = new FileInputStream(fname);
bufferInput = new BufferedInputStream(fileInput);
poiFileSystem = new POIFSFileSystem(bufferInput);
Biff8EncryptionKey.setCurrentUserPassword("secret");
final HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
final HSSFSheet sheet = workbook.getSheetAt(0);
final HSSFRow row = sheet.createRow(0);
final Cell cell = row.createCell(0);
cell.setCellValue("THIS WORKS!");
fileOut = new FileOutputStream(fname);
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
workbook.close();
}
catch (final Exception ex){
System.out.println(ex.getMessage());
}
finally{
try{
bufferInput.close();
}
catch (final IOException ex){
System.out.println(ex.getMessage());
}
try {
fileOut.close();
}
catch (final IOException ex) {
System.out.println(ex.getMessage());
}
}
// Recipient's email ID needs to be mentioned.
final String to = "example#example.com";
// Sender's email ID needs to be mentioned
final String from = "example#example.com";
final String username = "example";//change accordingly
final String password = "example";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
final String host = "example";
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "example");
// Get the Session object.
final Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
final 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
final Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
final String filename = "sample.xls";
final 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....");
} catch (final MessagingException e) {
throw new RuntimeException(e);
}
I believe I was not doing the encryption correctly. I used the code here instead: http://www.quicklyjava.com/create-password-protected-excel-using-apache-poi/. It resolved the issue.
This question already has answers here:
Send mail to multiple recipients in Java
(12 answers)
Closed 5 years ago.
Below is the java program which send a mail through java mail api now the issue is that I want to enter multiple addresses into mailTo field. In the below code, you can see there is single entry for mailTo that is avdq#abc.com. However, I want to pass multiple entries as avdq#abc.com, tvdq#abc.com, and pvdq#abc.com. Please advise how to achieve this.
public class abcMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdq#abc.com";
//String mailCc = "avdg#abc.com ";
String mailFrom = "avdg#abc.com";
String mailSubject = "sgdtetrtrr";
String mailText = "Test Mail for mail body ";
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(true);
//creating the message
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Address[] cc = new Address[] {
new InternetAddress("avdg#abc.com"),
new InternetAddress("sWER#gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\abc.pdf";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You just need to do the same thing as what you did for cc field
Address[] to = new Address[] {InternetAddress.parse("avdq#abc.com"),
InternetAddress.parse("tvdq#abc.com"),
InternetAddress.parse("pvdq#abc.com")};
message.addRecipients(Message.RecipientType.TO, to);
Try this
String cc = "avdg#abc.com;sWER#gmail.com";
StringTokenizer st = new StringTokenizer(cc,":");
while(st.hasMoreTokens()) {
emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(st.nextToken(),false);
}
I have developed a java mail api program which will send the mail and it also attaches the pdf file , so finally a mail is delivered in which pdf file is attached .
now can you please advise i want to make that pdf file as password protected through my java program itself for example i want to modify my below program such as that for opening an pdf file password 1234 is created and whenever an mail is sent the client should open the pdf file but before opening he should enter 1234 in the pop up box of pdf file to see it , can you please advise how can i achieve this in java program itself please. Thanks in advance below is my java program
public class BrokMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdg#abc.com";
//String mailCc = "avdg#abc.com ";
String mailFrom = "avdg#abc.com";
String mailSubject = "*****%%%%%%%%*********Email POC Brokerage for Rel 14.0****%%%%%%%%********";
String mailText = "Test Mail for Brokerage POC";
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse("avdg#abc.com"));
Address[] cc = new Address[] {
new InternetAddress("avdg#abc.com"),
new InternetAddress("saxenasaral#gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
//emailMessage.setContent(text, "text/html");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Now set the actual message
messageBodyPart.setText("This is message body");
//emailMessage.setContent(emailMessage, "text/html");
//emailMessage.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "c:\\SettingupRulesin outlook2003.pdf";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
// Set text message part
multipart.addBodyPart(messageBodyPart);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Taken from the tutorial: http://itextpdf.com/examples/iia.php?id=219
public static byte[] USER = "password 1234".getBytes();
public static byte[] OWNER = "password 1234".getBytes();
public void encryptPdf(String filename, String filename) throws IOException, DocumentException {
PdfReader reader = new PdfReader(filename);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileName));
stamper.setEncryption(USER, OWNER,
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
}
Add encryptPdf(fileName, fileName); after the file string has been declared.
Edit: Used byte[] objects for password names. The usage of strings have been deprecated from this version of iText for encryption purposes.