I have an excel sheet with one of the sheet as 'summary' which has summary of the execution, I am using javax mail to send this excel as attachment using outlook, however I would like to paste this summary in the email body so users get a summary before opening the excel.
I have tried with opening the excel and capturing the screen shot but whole excel is captured I only need whats inside excel.
I dont want to use VBA as the excel sheet may change.
Below is the code I am using for sending email:
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
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.testng.annotations.Test;
public class EmailExecutionReport {
static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
static Date date = new Date();
static String attachFiles="C:\\Excel_Report.xls";
static String messageToBeSent="<body > <p><font face="+"calibri"+">Hi All,</font></p><p><font face="+"calibri"+">Please find the Environment validations report as in the attached file</font></p><p><font face="+"calibri"+">This set of execution was completed on: "+dateFormat.format(date)+"</font></p><br><font face="+"calibri"+">Regards<br><font face="+"calibri"+"><br><br>---This is a auto generated email---</body>";
#Test
public static void JavaSentEamil() throws IOException {
// String host="host";
final String user="SSS#abcd.com";
String to="icpm-qa#abcd.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host","abcd.abcd.com");
props.put("mail.smtp.auth", "false");
Session session=Session.getDefaultInstance(props, null);
session.setDebug(true);
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.saveChanges();
message.setFrom(new InternetAddress(user));
//message.addRecipient(Message.RecipientType.TO,new InternetAddress (to));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Automation Environment validations Report as on: "+dateFormat.format(date));
// message.setText("This is test mail sent from Java Program");
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageToBeSent, "text/html ; charset=ISO-8859-1");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null) {
MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(attachFiles);
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("Message sent successfully...");
}
catch (MessagingException e) {e.printStackTrace();}
}
}
I am not sure why you are not using Excel POI and using the ChartSheet object there. But just to give you an idea here is already an existing discussion
How to get chart info from an Excel spreadsheet using Apache POI?
Related
I have a regular Java Application that works with Javamail. As in, if I just run it in a Main(String[] args) it will work but if I'm running it from a webapp, specifically VAADIN with Tomcat (AND Jetty), I always get a java.net.SocketException: network is unreachable: connect
I can ping the MSExchange server. And the regular program works.
In eclipse, I tried following this guide by changing the server.xml and web.xml settings, but after adding in all th changes, I still get the same error.
This is the Java Application that works in Eclipse, it will send an email using the MSExchange server we have. Are there specific ports I need to add? I've tried to force Tomcat to use IPV4 by adding 0.0.0.0 to all my connectors but that didn't do anything.
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import java.text.SimpleDateFormat;
public class SendEmail {
public static void main(String[] args) {
//Creates a connection with the Exchange Server.
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "email#host.com", "Test <b>Email</b>");
Here is the SendEmailUtility:
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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 SendEmailUtility {
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
//Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("blah#test.com"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail));
// Set Subject: header field
message.setSubject(subject);
// This mail has 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<img src=\"cid:image\"><p>"+body;
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
String fdsImg;
fdsImg = "c:\download.jpg";
DataSource fds = new FileDataSource(fdsImg);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
// Send message
Transport.send(message); //ERROR HAPPENS HERE ON TOMCAT
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This is the exactly same copy pasted code in the webapp with the exact same EmailUtils above, only that this version DOESN'T WORK.
btnSendEmail.addClickListener(new ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
try {
String smtpHostServer = "MSExchangeServerName";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.socketFactory.port", "25");
props.put("java.net.preferIPv4Stack","True");
Session session = Session.getInstance(props, null);
String todayStr = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 14);
Date d = c.getTime();
String dateStr = new SimpleDateFormat("MM/dd/yyyy").format(d);
SendEmailUtility.sendEmail(session, "blah#test.com", "test <b>email");
} catch (Exception e) {
e.printStackTrace();
Notification.show("Error sending the email", Notification.Type.ERROR_MESSAGE);
}
}
});
layout.addComponent(btnSendEmail);
My Stacktrace:
javax.mail.MessagingException: Could not connect to SMTP host: MSExchangeName, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.test.EmailUtils.sendEmail(EmailUtils.java:57)
Are there any other options I have to do or that I might not have done correctly? As a shot in the dark, I tried looking up eclipse, javamail, tomcat and I got this question and added the Javamail jar to my Tomcat Lib folder and also in my classpath. I still get the cannot connect error.
When I Right Click > Run as >Run on server, I tried to see if Tomcat was running on a system account, but when I checked in Task Manager, it had my Username under here:
Does this mean it has access to the network? Or something is still blocked? Or I need to add proxy settings specifically for Tomcat?
Sounds like a firewall or anti-virus problem. The JavaMail FAQ has connection debugging tips.
I'm not a very experienced coder, but I have been learning. Right now I am in the process of writing a test email bot to, well, send emails. I ran across a problem when I tried to make it so you could type out the message and subject of the email in a JOptionPane Dialog box.
Here is the code, look at the Strings at the top and the messageobjs at the bottom..
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;
import javax.swing.JOptionPane;
public class Ebot2
{
public static void main(String[] args)
{
String Dest;
Dest = JOptionPane.showInputDialog("Who would you like to message?");
String Subject;
Subject = JOptionPane.showInputDialog("What is the message subject?");
String Message;
Message = JOptionPane.showInputDialog("What is the message?");
String sendrmailid = "email#gmail.com";
final String uname = "email";
final String pwd = "pass";
Properties propvls = new Properties();
propvls.put("mail.smtp.auth", "true");
propvls.put("mail.smtp.starttls.enable", "true");
propvls.put("mail.smtp.host", "smtp.gmail.com");
propvls.put("mail.smpt.port", "25");
Session sessionobj = Session.getInstance(propvls,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(uname, pwd);
}
});
try
{
Message messageobj = new MimeMessage(sessionobj);
messageobj.setFrom(new InternetAddress(sendrmailid));
messageobj.setRecipients(Message.RecipientType.TO,InternetAddress.parse(Dest));
messageobj.setSubject(Subject);
messageobj.setText(Message);
Transport.send(messageobj);
System.out.println("Your email sent successfully....");
}
catch (MessagingException exp)
{
throw new RuntimeException(exp);
}
}
}
sorry for the shit formatting, the code block thing was difficult. Anyways the error Im getting started, after I changed the setSubject and setText to Strings that are entered through a JOptionPane. And the error is..
Ebot2.java:53: error: cannot find symbol
messageobj.setRecipients(Message.RecipientType.TO,InternetAddress.parse(Dest));
^
symbol: variable RecipientType
location: variable Message of type String
1 error
Thanks to anyone who answers, I really need help on this!
I fixed it guys. The problem was I had the String for the message set as Message (same problem with subject) which was also a variable. So I just renamed the string and it all worked. Thanks for the help anyways, glad to know I can go to this site for questions.
Next I'm going to try to figure out how to send the email multiple times, but I should be able to figure that out on my own.
I have an Android app which sends an e-mail message. But when I want to send an e-mail, my program totally crashes and I get the error:
Process: com.example.jonas.shoppinglist, PID: 16791
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NoClassDefFoundError: javax.activation.DataHandler
at javax.mail.internet.MimeMessage.setContent(MimeMessage.java:1508)
at javax.mail.internet.MimeBodyPart.setText(MimeBodyPart.java:1155)
at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1547)
at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1531)
Now I show the code of the e-mail sender, the problem line is message.setText("the actual text");
import android.util.Log;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.*;
public class MailSender {
private String body;
public void send() {
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
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("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I already did some research and people say it's a gradle issue, but I think I have all needed dependencies.
This is my gradle depencies:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.google.android.gms:play-services-gcm:7.3.0'
compile 'javax.activation:activation:1.1'
compile 'javax.mail:mail:1.5.0-b01'
compile 'javax.activation:activation:1.1.1'
}
What is going wrong?
You are using a Java library (javax.mail:mail:1.5.0-b01) that might not be suited for Android. There is an Android version of javamail:
https://code.google.com/p/javamail-android/ you should try that out. Don't expect that every library that works on Java will work on Android.
I am quite new in programming, sorry for weak explanation. I have tried with almost all available answers in google. but could not figure out why the error is coming.The purpose of this code is to attach a file and send it to a email address. I dont have any email server.
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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 SendEmailMain {
public static void main(String[] args) {
final String username = "myusername#gmail.com";
final String password = "mypassword";
String emailID = "receiversUserName#yahoo.com";
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 {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(emailID));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "snap1.jpg";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Error message in eclipse console
Sending
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. of6sm3574020lbb.11 - gsmtp
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at me.screenful.screenshot.ScreenShotTaker.SendEmailMain.main(SendEmailMain.java:70)
I have found why it was not working. Because I copied the code from google to my project. In the code
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.auth", true);
value true was not in inverted comma. It should be like this
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
If error come "530 5.7.0 Must issue a STARTTLS command first." at run time.
In IDE:
Right click the project. Click Run as then Run Configurations.
You can set the parameters "-Dmail.smtp.starttls.enable=true" in the (X)= Arguments tab in the VM Arguments box.
Click Run button.
or
At Command prompt:
You're giving parameters to java program
java -Dmail.smtp.starttls.enable=true <>.java
I am getting this error when tried to read mail using JavaMail. please let me know how to resolve this error. I have added activation.jar and mail.jar into eclipse.
DEBUG POP3: server doesn't support TOP, disabling it
javax.mail.AuthenticationFailedException: Command is not valid in this state.
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:174)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at library.VerifyEmail.main(VerifyEmail.java:40)
Below is the code I am trying:
package library;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.pop3.POP3Store;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SubjectTerm;
import javax.activation.*;
import java.io.*;
public class VerifyEmail {
public static void main(String[] args) throws Exception {
// SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
String host = "myhost";
// SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
String user = "myuser";
String password = "mypass";
// Get a session. Use a blank Properties object.
Session session = Session.getInstance(new Properties());
try {
// Get a Store object
Store store = session.getStore("pop3");
store.connect(host, user, password);
// Get "INBOX"
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_WRITE);
int count = fldr.getMessageCount();
System.out.println(count + " total messages");
// Message numebers start at 1
for(int i = 1; i <= count; i++) {
// Get a message by its sequence number
Message m = fldr.getMessage(i);
// Get some headers
Date date = m.getSentDate();
Address [] from = m.getFrom();
String subj = m.getSubject();
String mimeType = m.getContentType();
System.out.println(date + "\t" + from[0] + "\t" +
subj + "\t" + mimeType);
}
}catch (MessagingException ioex) {
ioex.printStackTrace();
}
}
}
When you're getting the javax.mail.AuthenticationException it means that your application is unable to authenticate to the mail server.
One possible reason for this might be that an SSL certificate of the mail server is missing from the client keystore.
According to microsoft: For exchange 2010, by default, the server would need the client use ssl for pop3.
Without ssl the server responds with "ERR command is not valid in this state."
Here's how to use javamail with ssl - Javamail and Gmail Pop3 SSL
DEBUG POP3: server doesn't support TOP, disabling it
this message can be disable by updating the java mail jar version to 1.4.4