I have successfully followed tutorials of how to embed images into HTML with javamail. However i am now trying to read from a template html file and then embed images into this before sending.
I am sure that the code is right for the embedding images as when i use:
bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
"<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
The images display fine. However when i read from a file using:
readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();
bodyPart.setContent(str, "text/html");
The images do not show up when the email sends.
My code for reading the html to string is as follows:
public class readHTMLToString {
static String finalFile;
public static String readHTML() throws IOException{
//intilize an InputStream
File htmlfile = new File("C:/temp/basictest.html");
System.out.println(htmlfile.exists());
try {
FileInputStream fin = new FileInputStream(htmlfile);
byte[] buffer= new byte[(int)htmlfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
String s = new String(buffer, "UTF-8");
finalFile = s;
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
return finalFile;
}
}
My complete class for sending the email is as follows:
package com.bcs.test;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 SendEmail {
public static void main(String[] args) throws IOException {
final String username = "usernamehere#gmail.com";
final String password = "passwordhere";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "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 {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recepientemailhere"));
message.setSubject("Testing Subject");
//SET MESSAGE AS HTML
MimeMultipart multipart = new MimeMultipart("related");
// Create bodypart.
BodyPart bodyPart = new MimeBodyPart();
// Create the HTML with link to image CID.
// Prefix the link with "cid:".
//bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
// "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();
// Set the MIME-type to HTML.
bodyPart.setContent(str, "text/html");
// Add the HTML bodypart to the multipart.
multipart.addBodyPart(bodyPart);
// Create another bodypart to include the image attachment.
BodyPart imgPart = new MimeBodyPart();
// Read image from file system.
DataSource ds = new FileDataSource("C:\\temp\\dice.png");
imgPart.setDataHandler(new DataHandler(ds));
// Set the content-ID of the image attachment.
// Enclose the image CID with the lesser and greater signs.
imgPart.setDisposition(MimeBodyPart.INLINE);
imgPart.setHeader("Content-ID","the-img-1");
//bodyPart.setHeader("Content-ID", "<image_cid>");
// Add image attachment to multipart.
multipart.addBodyPart(imgPart);
// Add multipart content to message.
message.setContent(multipart);
//message.setText("Dear Mail Crawler,"
// + "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Ive read through numerous answers about this but really not sure why this is happening. I thought it was because of an issue with my html file however i created a very basic one using the same content as the initial setContent code above and the pictures dont appear in this basic example.
Something to do with reading into a byte array?
Any help greatly appreciated.
Thanks
The way email clients interpret HTML code is different from writing to HTML template file. But one thing you could try for sure is once you get the template, copy the byte array of the image to the src attribute. You could try with inline images as browser inteprets src attribute and make another request to get the data.
Gives you a lot more insight in to the concept.Inline Images in HTML
Of course you need to make sure that the data in the file is actually encoded in UTF-8 and not in the default encoding for your computer. If you test this with all ASCII text, it shouldn't matter.
Assuming you have the same text in the file that you have in the string in the sample code above, you can compare the two cases (string, file) to see how the messages JavaMail would send differ by using message.writeTo(new FileOutputStream("msg.txt")); just before or in place of the Transport.send call.
Related
Can any one help me with a java code where i want that my html code to be added in body of the mail and the mail client should pop up so that a person can enter the To: and can edit the body if needed.
I have tried this code but this one just sends the mail.What i want is the my mail client should popup with body already entered.
package you;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import javax.mail.BodyPart;
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;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
public class test1 {
public void fnSendMail(String Status) throws IOException, InvalidFormatException, URISyntaxException {
String htmlContent = null;
if (Status.equals("Completed")) {
htmlContent = "<html><br>Below is Test Execution Report.<br>Please find the attached for Detailed Results"
+ "<br><br><table border='1' cellpadding='2' cellspacing='3' width='40%' bordercolor='#999999' style='border-collapse: collapse;'>"
+ "<tr><th>SNo</th><th>Run_Method</th><th>abc_name</th><th>Execution_Status</th></tr>" + "</table>"
+ "<br><br><br><h3 style='color:FireBrick;'>Please do not respond to this mail </h3></html>";
} else {
htmlContent = "<html><br>" + "<h3 style='color:FireBrick;'>Automation got failed due to some issue, hence "
+ "Please verify Maven Errors.<br><br>Execution Status till failure is attached.</h3></html>";
}
String from = "abc#cdf.com";
String host = "x.y.z";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
Multipart multipart = new MimeMultipart();
BodyPart messageBodyText = new MimeBodyPart();
message.setSubject("CSI API Automated Testing Report is " + Status);
messageBodyText.setContent(htmlContent, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
test1 test2= new test1();
try {
test2.fnSendMail("Completed");
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
}
Any other way to do this will also work, but i need is java and javascript only
Instead of calling Transport.send you have to call MimeMessage.saveChanges then use MimeMessage.writeTo to save it to the filesystem as '.eml'. Then open that file with java.awt.Desktop.open to launch the email client. Your system must have a mime association with eml or the open call will fail.
If the O/S mime type for eml is not set to something like outlook.exe /eml %1 then you might have to resort to using the process API to launch outlook directly using the eml switch. For example, if you want to preview the foo.eml draft message then the command would be:
outlook.exe /eml foo.eml
You'll have to handle clean up after the email client is closed.
You also have to think about the security implications of email messages being left on the file system.
In this example Im trying to send an attachment via mail using gmail smtp server.
Mailer.java
package com.servlet.mail;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
public class Mailer {
public static void send(String to ,String subject ,String msg)
{
System.out.println("in Mailer class");
final String user="sup.ni#gmail.com";
final String psw="XXXXXX";//changes to be made accoordingly
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,psw);
}
});
try
{
System.out.println(to+""+subject+""+msg);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
//message.setText(msg);
//Mail sending with attachement
BodyPart msgBodyPart1 = new MimeBodyPart();
msgBodyPart1.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgBodyPart1);
MimeBodyPart msgBodyPart2 = new MimeBodyPart();
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String filename= path+"Note.txt";
System.out.println(path);
message.setHeader("Content-Disposition", "attachement ; filename= \""+filename+"\"");
DataSource src = new FileDataSource(filename);
msgBodyPart2.setDataHandler(new DataHandler(src));
msgBodyPart2.setFileName(path);
multipart.addBodyPart(msgBodyPart2);
message.setContent(multipart);
//SEND MSG
Transport.send(message);
System.out.println("Mail sent successfully");
}
catch(MessagingException e)
{
System.out.println(e);
}
}
}
The requirement is that I want the attachment name to be just the file name.
Here in this example when I check the mail the attachment will have absolute path.
This is the file-name I receive in the attached file "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/Note.txt"
But I want the attached file to be just Note.txt
Please let me know what is changes has to be done in order to get my required output
You're setting the filename in the header using the filename= \".....\" key-value pair. Just change this value to the name you want to set.
For example:
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String name = "Note.txt";
String filename= path+name;
message.setHeader("Content-Disposition", "attachement ; filename= \""+name+"\"");
I've started to build a service monitor using SoapUI 5 (non-Pro edition). The service monitor should be able to:
Teststep1 (http Request): Call an URL, which genereates a token
Teststep2 (groovy script): Parse the response and save the token as a property
Teststep3 (http Request): Call another URL
Teststep4 (groovy script): Parse the repsonseHttpHeader, save the statusHeader in a testCase-property and check if it is '200', '400', '403'...
Teststep5 (groovy script): Write an email whenever it is not '200'
Steps 1 to 4 are working without any problems and also sending emails (step 5) by executing my script is working, but I would like to change the email content depending and the statusHeader. For example:
404: The requested resource could not be found
403 : It is forbidden. Please check the token generator
...
Code for parsing and saving httpHeaderStatusCode:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
// get responseHeaders of ServiceTestRequest
def httpResponseHeaders = context.testCase.testSteps["FeatureServiceTestRequest"].testRequest.response.responseHeaders
// get httpResonseHeader and status-value
def httpStatus = httpResponseHeaders["#status#"]
// extract value
def httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
// log httpStatusCode
log.info("HTTP status code: " + httpStatusCode)
// Save logged token-key to next test step or gloabally to testcase
testRunner.testCase.setPropertyValue("httpStatusCode", httpStatusCode)
Code for sending email:
// From http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "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 {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
What I want to do: I want to access the testCase httpStatusCode property saved on my first groovy script (last line) in my last groovy script where I send my email. Is there something, which can handle this?
I've searched for two hours, but I have't found something useful. A possible workaround would be that I have to call different Email-Scripts with different messages using if statements and the testRunner.runTestStepByName method, but changing the content of the email would be nicer.
Thanks in advance!
You have to change your class definition in the last groovy script, instead of main define a method to send the email which has statusCode as parameter in your sendMailTLS class. Then in the same groovy script where you define your class use def statusCode = context.expand('${#TestCase#httpStatusCode}'); to get your property value and then create an instance of your class and invoke your method passing the property statusCode with:
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
All together in your groovy script have to look like:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// define the class
class SendMailTLS {
// define a method which recive your status code
// instead of define main method
public void sendMail(String statusCode) {
final String username = "yourUsername#gmail.com";
final String password = "yourPassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "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 {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourSendFromAddress#domain.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yourRecipientsAddress#domain.com"));
message.setSubject("Status alert");
// THERE YOU CAN USE STATUSCODE FOR EXAMPLE...
if(statusCode.equals("403")){
message.setText("Hey there,"
+ "\n\n You recive an 403...");
}else{
message.setText("Hey there,"
+ "\n\n There is something wrong with the service. The httpStatus from the last call was: ");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
// get status code
def statusCode = context.expand('${#TestCase#httpStatusCode}');
// create new instance of your class
def mailSender = new SendMailTLS();
// send the mail passing the status code
mailSender.sendMail(statusCode);
I test this code and it works correctly :).
Hope this helps,
Here is what you can do:
Add a map in your java class which contains all the expected
Response codes, and Response Messages as you wanted to have either
subject or content of email.
I would suggest you to have it in a method other than main so that
you intiantiate class object and call method from soapui's groovy
script, of course you do it with main as well.
Method should take response code as argument.
Use it as key to get the relevant value from the map and put it to
email.
Create a jar file for your class and put jar file under
$SOAPUI_HOME/bin/ext directory
In your soapui test case, for test step5 (groovy) call your method
from the class you wrote like how you call in java. For example: How
to call your java from soapui groovy given below
//use package, and imports also if associated
SendMailTLS mail = new SendMailTLS()
//assuming that you move the code from main method to sendEmail method
mail.sendEmail(context.expand('${#TestCase#httpStatusCode}')
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I want to generate a PDF document from a "raw" email. This email could containt html or just text. I don't care for attachments.
The resulting pdf should contain the proper formatting (from css and html) and also embedded images.
My first idea was to render the email using an email client like thunderbird and then print it to pdf. Does thunderbird offer such an API or are there java libraries available to print an email to pdf?
I've found a better solution to the one I posted before. saving the email to html, then use jtidy to clean it up to xhtml. and lastly use flying saucer html renderer to save it into pdf.
Here is an example I wrote:
import com.lowagie.text.DocumentException;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Email2PDF {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
//read your latest email
store.connect("imap.gmail.com", "youremail#gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
String filename = msg.getSubject();
FileOutputStream os = new FileOutputStream(filename + ".html");
msg.writeTo(os);
//use jtidy to clean up the html
cleanHtml(filename);
//save it into pdf
createPdf(filename);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void cleanHtml(String filename) {
File file = new File(filename + ".html");
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(filename + ".xhtml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Tidy tidy = new Tidy();
tidy.setQuiet(false);
tidy.setShowWarnings(true);
tidy.setShowErrors(0);
tidy.setMakeClean(true);
tidy.setForceOutput(true);
org.w3c.dom.Document document = tidy.parseDOM(in, out);
}
public static void createPdf(String filename)
throws IOException, DocumentException {
OutputStream os = new FileOutputStream(filename + ".pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new File(filename + ".xhtml"));
renderer.layout();
renderer.createPDF(os) ;
os.close();
}
}
Enjoy!
I put a piece of software together that converts eml files to pdf's by parsing (and cleaning) the mime/structure, converting it to html and then use wkhtmltopdf to convert it to a pdf file.
It also handles inline images, corrupt mime headers and can use a proxy.
The code is available at github under apache V2 license.
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
public class Email2PDF {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "youremail#gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
createPdf(msg.getSubject(), (String) bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void createPdf(String filename, String body)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf"));
document.open();
document.add(new Paragraph(body));
document.close();
}
}
I've used itext as the pdf library
You can read HTML content using email client and then use iText to convert it in to PDF
Look into fpdf and fpdi, both free libraries for PHP are used in the creation of PDF docs.
Since the SMTP protocol has conventions, actually strict rules, you can always count on the first empty line to be the before the content of the message. So you can definitely parse everything after the first part of the line to get the entirety of the message.
For embedded images, you'll need a base 64 decoder (usually) or some other decoder based on the email's attachment encoding type to transform the data into a human readable image.
You could try the Apache PDFbox library.
It seems to have a nice API and it also supports printing. PrintPDF
You would have to run the print command from CLI with your file as a parameter.
Edit: It is Java and open-source.
Hope it helps!
As subject is self explanatory - I am facing issue in sending email to a group email using java mail.
I have gone through through several blogs & articles which are of no help & does not have a precise answer or hangs in middle.
Can you please help. Here is my mail class for you. My mail is going to have a link to ftp location & a text file as an attachment.
To separate the issue i tried to send a simple mail to the group as well but that didn't help either.
I tried to find answers in places like java-forums.org & Stack overflow but found no luck.
I appreciate your quality time & help in providing an insight to the issue.
To explain the issue better-
My Automation framework when completes the execution of test cases, it sends a mail to me with the link to execution report & a log file as an attachment. Now the audience for the report has expanded & we need to send the mail to a group email address.
When I set the email (to say group.email#company.com) none of the users in the group receives the mail. Where as if I send the email to my email address or anyone else email address it works.
I get no logs or error for this & so I am not able to understand the issue correctly.
An insight from the experts will help in understanding the issue.
Thanks in advance.
Akshat
import java.util.ArrayList;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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 ReportMail {
private MimeMessage message = null;
private Session emailSession = null;
private MimeBodyPart textPart = null;
private ArrayList<MimeBodyPart> attachmentArray = null;
public void sendMailer(String mailToId, String string, String mailServer1,
int mailPort, String mailAdmin) {
Properties mailProperties = null;
mailProperties = new Properties();
String adminEmailId = mailAdmin;
String mailServer = mailServer1;
mailProperties.put("mail.transport.protocol", "smtp");
//mailProperties.put("mail.smtp.auth", "true");
mailProperties.put("mail.smtp.host", mailServer);
mailProperties.put("mail.from", adminEmailId);
mailProperties.put("mail.smtp.port", mailPort);
mailProperties.put("mail.to", mailToId);
try {
emailSession = Session.getInstance(mailProperties);
emailSession.setDebug(false);
message = new MimeMessage(emailSession);
textPart = new MimeBodyPart();
attachmentArray = new ArrayList<MimeBodyPart>(2);
message.addRecipients(RecipientType.TO, mailToId);
message.setSubject(string);
message.setFrom(new InternetAddress(adminEmailId));
setContent("PCM Automation Report");
//setContent("test123");
sendEMail();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setContent(String content) {
try {
textPart.setContent(content, "text/html");
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean sendEMail() throws Exception {
try {
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
for (int i = 0; i < attachmentArray.size(); i++)
mp.addBodyPart(attachmentArray.get(i));
/********************
*
*/
// Part two is attachment
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Below is the link for the Test Automation report as link & attached Log file. PFA.");
//mp.addBodyPart(messageBodyPart);
String filename = "logfile.log"; //C:\workspacePCMSanity\PCMSanity\logfile.log
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
mp.addBodyPart(messageBodyPart);
/**
*
*/
message.setContent(mp);
Transport transport = emailSession.getTransport();
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return true;
}
}
In Microsoft Exchange Server there is a special group address setting option Require that all senders are authenticated. When an unknown user is used as a sender, such an email is rejected. You can either send emails in the name of real user or enable this option. In the latter case the group address is opened to spam.
http://technet.microsoft.com/en-us/library/bb124405%28v=exchg.141%29.aspx
Java doesn't know whether an email address is for a single user or a group.
Probably the issue with SMTP Server.