Issue in sending email to a group email using java mail - java

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.

Related

Sending EMail with Javamail via Exchange Server

we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(properties);
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("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.

How to open outlook mail from java with prepoulaed body with html code

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.

How to send mail in Java using same mechanism like in PHP mail()

I'm having trouble in sending mail from my application. I can't use simple SMTP server on my application. And have no idea how to deal with sending mails in JAVA. I'm supposed to use same/similar mechanism like PHP's mail() uses. Unfortunately I have no idea how to do it.
The Java Mail API provides support for sending and receiving e-mails. The API provides a plug-in architecture where vendor’s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols:
Internet Mail Access Protocol (IMAP)
Simple Mail Transfer Protocol (SMTP)
Post Office Protocol 3 (POP 3)
Here is an example of how to use it:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public static void main(String[] args) {
String from = "abc#gmail.com";
String to = "xyz#gmail.com";
String subject = "Test";
String message = "A test message";
SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You need to check out the JavaMail API, and as PHP's mail() requires, it will need an SMTP server to send that email.
If you require an SMTP server I suggest searching Google for an SMTP server for your operating system or maybe you could use an SMTP server provided by your ISP or server host.
You can use JavaMail api with a local SMTP server like Apache James, so after installing and running James server, you can set the SMTP server ip to 127.0.0.1
I'm supposed to use same/similar mechanism like PHP's mail() uses.
You can't, because it doesn't exist. If that's the requirement, get it changed.
Unfortunately I have no idea how to do it.
See the JavaMail API.

Embedded images not showing in email from Javamail html template

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.

How do I send an SMTP Message from Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you send email from a Java app using Gmail?
How do I send an SMTP Message from Java?
Here's an example for Gmail smtp:
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;
public class Distribution {
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtps.host","smtp.gmail.com");
props.put("mail.smtps.auth","true");
Session session = Session.getInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("mail#tovare.com"));;
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("tov.are.jacobsen#iss.no", false));
msg.setSubject("Heisann "+System.currentTimeMillis());
msg.setText("Med vennlig hilsennTov Are Jacobsen");
msg.setHeader("X-Mailer", "Tov Are's program");
msg.setSentDate(new Date());
SMTPTransport t =
(SMTPTransport)session.getTransport("smtps");
t.connect("smtp.gmail.com", "admin#tovare.com", "<insert password here>");
t.sendMessage(msg, msg.getAllRecipients());
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache
http://commons.apache.org/email/
Regards
Tov Are Jacobsen
Another way is to use aspirin (https://github.com/masukomi/aspirin) like this:
MailQue.queMail(MimeMessage message)
..after having constructed your mimemessage as above.
Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.
Please see this post
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
It is specific to gmail but you can substitute your smtp credentials.
See the following tutorial at Java Practices.
http://www.javapractices.com/topic/TopicAction.do?Id=144
See the JavaMail API and associated javadocs.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail(String recipients[], String subject,
String message , String from) throws MessagingException {
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}

Categories