Draft gmail attachments appear in trash folder when javamail is used - java

I'm using javamail to read emails from gmail Trash folder and if there is email in Draft folder with attachments then these attachments appear in Trash folder.
Steps to reproduce:
1) create new email with attachment(s) and close it, it appears in Draft folder. 2) Read emails from Trash folder using program below. Attachment(s) from draft email appear. If I open Trash folder in browser I don't see these attachments. Do you know why attachment appear in Trash folder when emails are read using javamail?
import java.io.IOException;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class MailClient {
public static void main(String[] args) throws Exception {
MailClient client = new MailClient();
client.execute();
}
void execute() throws MessagingException, IOException {
String[] credentials = new String[] {"name#gmail.com", "password"};
boolean debug = false;
Folder folder = null;
Store store = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
store = session.getStore("imaps");
store.connect("imap.gmail.com", credentials[0], credentials[1]);
folder = store.getFolder("[Gmail]/Trash");
folder.open(Folder.READ_WRITE);
Message messages[] = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
for (int i = 0; i < messages.length; ++i) {
System.out.println("MESSAGE #" + (i + 1) + ":");
Message msg = messages[i];
String from = "unknown";
if (msg.getReplyTo().length >= 1) {
from = msg.getReplyTo()[0].toString();
} else if (msg.getFrom().length >= 1) {
from = msg.getFrom()[0].toString();
}
String subject = msg.getSubject();
System.out.println(subject);
msg.setFlag(Flags.Flag.SEEN, true);
}
} finally {
if (folder != null) {
folder.close(true);
}
if (store != null) {
store.close();
}
}
}
}

Your program doesn't do anything with attachments. Why do you believe the attachments for the draft message, but not the message itself, appear in the Trash folder? And what message in the Trash folder are those attachments attached to?
How are you creating the Draft message? Through the Gmail web interface? Is it possible that Gmail is saving multiple drafts of your draft message, and the old drafts are being moved into the Trash folder, with only the latest draft left in the Drafts folder?

Related

How to let javamail support http proxy

I found that javamail only support socks. Is there any solution I can use to support http proxy?
public class MailConnectionTest {
public static void main(String args[]) throws MessagingException {
Properties props = MailConnectionTest.getProperties();
Session session = Session.getDefaultInstance(props, null);
String protocol = "pop3";
String host = "pop.163.com";
String username = "email username";
String password = "1Qaz2wsx3edc&";
Store store = session.getStore(protocol);
store.connect(host, username, password);
System.out.println("Success");
}
private static Properties getProperties() {
Properties props = System.getProperties();
props.put("mail.debug", "false");
// Proxy
props.put("proxySet", "true");
props.put("http.proxyHost", "proxyAdderss");
props.put("http.proxyPort", "8080");
return props;
}
}
As per the latest release of Javamail API 1.6.2 , JavaMail supports accessing mail servers through a web proxy server and also authenticating to the proxy server. Please see my code below.
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class ReadMailProxy {
public static void receiveMail(String userName, String password) {
try {
String proxyIP = "124.124.124.14";
String proxyPort = "4154";
String proxyUser = "test";
String proxyPassword = "test123";
Properties prop = new Properties();
prop.setProperty("mail.imaps.proxy.host", proxyIP);
prop.setProperty("mail.imaps.proxy.port", proxyPort);
prop.setProperty("mail.imaps.proxy.user", proxyUser);
prop.setProperty("mail.imaps.proxy.password", proxyPassword);
Session eSession = Session.getInstance(prop);
Store eStore = eSession.getStore("imaps");
eStore.connect("imap.mail.yahoo.com", userName, password);
Folder eFolder = eStore.getFolder("Inbox");
eFolder.open(Folder.READ_WRITE);
Message messages[] = eFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println(messages.length);
for (int i = messages.length - 3; i < messages.length - 2; i++) {
Message message = messages[i];
System.out.println("Email Number::" + (i + 1));
System.out.println("Subject::" + message.getSubject());
System.out.println("From::" + message.getFrom()[0]);
System.out.println("Date::" + message.getSentDate());
try {
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
} catch (Exception e) {
System.out.println("Content: " + message.getContent().toString());
}
message.setFlag(Flag.SEEN, true);
}
eFolder.close(true);
eStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
receiveMail("umesh#yahoo.com", "test123");
}
}
javamail api 1.6 supports web server proxy
set these properties
mail.protocol.proxy.host
mail.protocol.proxy.port
for smtp set as
mail.smtp.proxy.host
mail.smtp.proxy.port
See the JavaMail FAQ:
How do I configure JavaMail to work through my proxy server?
... Without such a SOCKS server, if you want to use JavaMail to access mail servers outside the firewall indirectly, you might be able to use a program such as Corkscrew or connect to tunnel TCP connections through an HTTP proxy server. JavaMail does not support direct access through an HTTP proxy web server.
The implementation only support basic authentication for web proxy. You can find the source code in com.sun.mail.util.SocketFetcher.
Since javamail support NTLM authentication already, it is not hard to support NTLM authentication for web proxy.

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.

Issue in sending email to a group email using java mail

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.

How to set Email Client in Java?

i'm trying the very simple Email Client in java.
When i launch the programe i have an error message:
Exception in thread "main" javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:146)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at SimpleEmailClient2.main(SimpleEmailClient2.java:21)
Java Result: 1
Why?
i use Gmail account and i set the POP and IMAP enabled
What could be the possible error in my code?
Thank you
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class SimpleEmailClient2 {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "pop.gmail.com";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, new MailAuthenticator());
Store store = session.getStore(provider);
store.connect(host, null, null);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("email#gmail.com", "password");
}
}
I don't believe gmail supports the pop3 provider; you have to use pop3s instead. Otherwise this should work fine.
Oracle has information on connecting javamail to gmail here.
Specifically it looks like you're failing when trying to establish the connection, likely because you don't specify a username/password to connect to. Try connecting using something like:
store.connect(host, "user618111#gmail.com", "[myPassword]");

Display .eml file in a web appication

I have a web application where I need to display .eml files (in RFC 822 format) to the users, formatted properly as e-mail - show the HTML to text body properly, show images, attachments and so on. Do you know of a component / library that can do those things?
I prefer it would be in Java (and to integrate with spring easily :-) ), but any other implementation which runs on Apache is fine as well.
Javamail can read EML file.
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ReadEmail {
public static void main(String args[]) throws Exception{
display(new File("C:\\temp\\message.eml"));
}
public static void display(File emlFile) throws Exception{
Properties props = System.getProperties();
props.put("mail.host", "smtp.dummydomain.com");
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream(emlFile);
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
}
}
Handle EML file with JavaMail
You could convert .eml into javax.mail.Messages mailMessage as:
Loading .eml files into javax.mail.Messages
then you could use this library to convert in MessageBean:
http://javaclue.blogspot.com/2009/09/portable-java-mail-message-bean_02.html
MessageBean mb = MessageBeanUtil.mimeToBean(mailMessage);

Categories