how to include signature in outlook javamail - java

I'm trying to create an email using javamail where i can attach many files and also configure the body message , destination and many settings... at the end i save this email in a temp file to use it in outlook 2016 where i can now open outlook and pass the eml file using outlook command line with switch /eml.
The problem is is a try to attach one file with outlook using the switch /a, i can see the signature the footer of the body message but when i use the created eml file i can not see any signature.
what i tried to do is to load the pre-saved signature in roaming folder from different format (htm, rtf and txt) with txt file there is no problem and can put it inside the message in eml file but using rtf i cannot visualize the content as i see in ms word, using the htm file the images (if exist) still not visible.
I'm wondering how i can use one of the two (html or rtf file) to include the signature in the bottom of the body message automatically.
Hope that someone already worked on the same subject.

I think you can take a snapshot of the signature and save it in a particular directory and send a HTML email by inserting the image . You can find something here on how you can send inline HTML images in the message body. Hope it helps.

The problem is mainly in the path's image included in the htm file, so I parsed the original path with the absolute one, so i can visualize the image correctly
public static String getSignature() throws IOException {
String content ="";
String appDataPath = System.getenv("APPDATA")+"\\Microsoft\\Signatures\\";
System.out.println(appDataPath);
File folder = new File(appDataPath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".htm")) {
content = FileUtils.readFileToString(file , "windows-1252");
content =content.replaceAll("src=\"", "src=\"" +appDataPath.replace("\\", "/"));
}
}
return content;
}
Then I retrieve the content and I put it inside the message that I want to send.
MimeBodyPart body = new MimeBodyPart();
body.setDisposition(MimePart.INLINE);
body.setContent(signature, "text/html");
mmp.addBodyPart(body);
I added some enhancement on the code:
public static String[] getSignature() throws IOException {
String content = "";
String appDataPath =System.getenv("APPDATA") + "\\Microsoft\\Signatures\\";
System.out.println(appDataPath);
File folder = new File(appDataPath);
File[] listOfFiles = folder.listFiles();
String imagePath ="";
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".htm")) {
content = FileUtils.readFileToString(file, "windows-1252");
content = content.replaceAll("src=\"", "src=\"" + appDataPath.replace("\\", "/"));
}else if(file.isDirectory()){
File[] listOfHtmlFiles = file.listFiles();
for (File f : listOfHtmlFiles) {
if(Files.probeContentType(f.toPath()).contains("image")) {
imagePath = f.getPath();
}
}
}
}
return new String[]{content,imagePath};
}
i this new code i retrieve the signature from html and the image path from html files folders.
Then i created image an image as joint file ( attached to the email)
then i modify src in the signature as follow :
MimeBodyPart imgBP = new MimeBodyPart();
DataSource fds = new FileDataSource(imgPath);
imgBP.setDataHandler(new DataHandler(fds));
imgBP.setHeader("Content-ID", "<image>");
mmp.addBodyPart(imgBP);
signature = signature.replaceFirst("(src=)([\"|\'])(.*)([\"|\'])",
"$1$2cid:image$4");
MimeBodyPart body = new MimeBodyPart();
body.setDisposition(MimePart.INLINE);
body.setContent("<br><br><br>" + signature, "text/html");
mmp.addBodyPart(body);

Related

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

Grails 3 Loading Static Files

I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}

How Can I extract the .dat file(contain image) using java API

if i using HMEFContentsExtractor in POI jar, it can extract html only it is not able extract the image content form winmail.dat(attchment mail sent from oulook), is there any jar file to do this & explain how to use that.
HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(winmailFilename));
File dir = new File(directoryName);
File rtf = new File(dir, "message.rtf");
if(! dir.exists()) {
throw new FileNotFoundException("Output directory "+dir.getName()+" not found");
}
HMEFMessage msg = new HMEFMessage(new FileInputStream(winmailFilename));
msg.getAttachments();ext.extractMessageBody(rtf);

Javamail attachments data lost

I use Javamail to save attachments in a temp Folder, code is given below :-
for (int i = 0; i < multipartmsg.getCount(); ++i) {
BodyPart bodypart = multipartmsg.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(bodypart.getDisposition())
&& null != bodypart.getFileName()
&& !bodypart.getFileName().isEmpty()) {
InputStream is = bodypart.getInputStream();
MimeBodyPart mbp = new MimeBodyPart(is);
File f = new File("/temp/"+abcd);
mbp.saveFile(f);
}
But a 250kB file gets saved as 220kB. There is a loss of data, hence I am unable to open the file. Any idea why this may be happening ?
I also set my properties.setProperty("mail.imaps.partialfetch", "false"); since I use imaps to connect.
Why are you creating a new MimeBodyPart with the content of the original part? That makes no sense, and is likely the source of your problem. Just use the saveFile method on the original part.

How to store uploaded mulitple pdf file to a specific location in java?

i want to store uploaded file in a specific location in java. if i upload a.pdf then i want it to store this at "/home/rahul/doc/upload/". i went through some questions and answers of stack overflow but i am not satisfied with solutions.
i am working with Play Framework 2.1.2. i am not working with servlet.
i am uploading but it is storing file into temp directory but i want that file store into a folder as not a temp file i want that file like a.pdf in folder not like temp file.
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
but i am not satisfied with this solution and i am uploading multiple doc files.
for eg. i upload one doc ab.docx then after upload it is storing temp directory and file is this:
and it's location is this: /tmp/multipartBody5886394566842144137asTemporaryFile
but i want this: /upload/ab.docx
tell me some solution to fix this.
Everything's correct as a last step you need to renameTo the temporary file into your upload folder, you don't need to play around the streams it's as simple as:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
BTW you should implement some checking if targetPath doesn't exist to prevent errors and/or overwrites. Typical approach is incrementing the file name if file with the same name already exists, for an example sending a.pdf three times should save the files as a.pdf, a_01.pdf, a_02.pdf, etc.
i just completed it. My solution is working fine.
My solution of uploading multiple files is :
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}

Categories

Resources