How to access to label folder in gmail using java? - java

We can read messages from gmail inbox but can we read from a label?
If I take the following example from http://harikrishnan83.wordpress.com/2009/01/24/access-gmail-with-imap-using-java-mail-api/
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 javax.mail.Store;
public class InboxReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}
If I change "inbox" by a label name it's throwing an error: inbox is not found.
Any help, please?

Try the following code which is working for me :
store.getFolder("FolderNameGoesHere");
private static Store getConnection() throws MessagingException {
Properties properties;
Session session;
Store store;
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("dummy#gmail.com",
"dummy");
}
});
store = session.getStore("imaps");
store.connect();
return store;
}
public static boolean isMailReceivedBySubject(String subject,String folder) throws MessagingException {
Store store = null;
boolean emailReceived = false;
try {
store = getConnection();
Folder mailFolder = store.getFolder(folder);
mailFolder.open(Folder.READ_WRITE);
SearchTerm st = new AndTerm(new SubjectTerm(subject), new BodyTerm(subject));
Message[] messages = mailFolder.search(st);
for (Message message : messages) {
System.out.println("message : " + message.getSubject());
if (message.getSubject().contains(subject)) {
System.out.println("Found the email subject : " + subject);
emailReceived = true;
break;
}
}
return emailReceived;
}finally {
if (store != null) {
store.close();
}
}
}

Related

trying to search a mail with subject in Gmail using java

My company mail domain is Gmail , and I need to search a mail using subject line. I have written below code but Gmail is not connecting with correct user id and password.
public static void getMail() {
Scanner sc = new Scanner(System.in);
final String m10 = "abc#abc.com";
final String n10 = "abcd";
String host = "absmtp.abc.com";
try
{
Properties pro1 = new Properties();
pro1.put("mail.smtp.host", host);
pro1.put("mail.smtp.socketFactory.port", "465");
MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
pro1.put("mail.imaps.ssl.socketFactory", socketFactory);
// pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// pro1.put("mail.smtp.auth", "true");
pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1);
Store store = session.getStore("imaps");
store.connect(host, m10, n10);
Folder folderbox = store.getFolder("INBOX");
folderbox.open(Folder.READ_ONLY);
SearchTerm search = new SearchTerm(){
#Override
public boolean match(Message message) {
try
{
if(message.getSubject().contains("") )
{
return true;
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
return false;
}
};
Message[] found = folderbox.search(search);
int length = found.length;
for(int i = 0;i<found.length;i++)
{
Message mess1 = found[i];
System.out.println("->Message Number > "+i);
System.out.println("->Message Subject >"+mess1.getSubject());
}
folderbox.close(true);
store.close();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
is not connecting and giving error :
Couldn't connect to host, port: abc#abc.com, 993; timeout -1.

Save email into sent folder using spring mail

I have a function to send email to customer to confirm order which customer has ordered.
Code:
#Bean
public JavaMailSender orderMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("mail.myserver.vn");
mailSender.setPort(25);
mailSender.setUsername(SystemParams.ORDER_EMAIL_ADDRESS);
mailSender.setPassword(SystemParams.ORDER_EMAIL_PASSWORD);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.store.protocol", "imaps");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.debug", "true");
return mailSender;
}
private void sendEmailConfirm(HttpSession session) {
try {
MimeMessage message = emailSender.createMimeMessage();
boolean multipart = true;
MimeMessageHelper helper = new MimeMessageHelper(message, multipart);
Object object = session.getAttribute(Constants.CART_CONFIRM_ATTRIBUTE_NAME);
String htmlMsg = "<h4>Đơn hàng #" + object + " đã được tạo thành công.<h4>";
message.setContent(htmlMsg, "text/html; charset=utf-8");
message.setSubject("Xác nhận đơn hàng #" + object, StandardCharsets.UTF_8.displayName());
message.setFrom(SystemParams.ORDER_EMAIL_ADDRESS);
helper.setTo("customeremail#gmail.com");
// helper.setSubject();
this.emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
All data I currently store in session. With this code, email sent successfully but it don't store in sent folder, How can I save sent email to sent folder in email server?
You may need to do it explicitly
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect(host, "user", "userpwd");
Folder folder = (Folder) store.getFolder("Sent");
if (!folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
System.out.println("appending...");
try {
folder.appendMessages(new Message[]{message});
// Message[] msgs = folder.getMessages();
message.setFlag(FLAGS.Flag.RECENT, true);
} catch (Exception ignore) {
System.out.println("error processing message " + ignore.getMessage());
} finally {
store.close();
folder.close(false);
}

Probleme with JavaMail

I integrated in my JavaMail application, allowing me to send an email via Java (I use Gmail) it works without problems but when I use it on another connection, it no longer works.
He shows me this error :
enter image description here
There is my Mail code :
public class SupportMail {
private static String LOGIN_SMTP1="login";
private static String PASSWORD_SMTP1="pwd";
private static String SMTP_HOST1="smtp.gmail.com";
private static String IMAP_ACCOUNT1="rollandgame#gmail.com";
private static String receiver = "floriangenicq#gmail.com";
private static String copyRecei = "floriangenicq#gmail.com";
public SupportMail() {
}
public static void sendMessage(String subject, String text) {
// Création de la session
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.put("mail.smtp.ssl.trust", SMTP_HOST1);
properties.setProperty("mail.smtp.host", SMTP_HOST1);
properties.setProperty("mail.smtp.user", LOGIN_SMTP1);
properties.setProperty("mail.from", IMAP_ACCOUNT1);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.port", 587);
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
// Création du message
MimeMessage message = new MimeMessage(session);
try {
message.setText(text);
message.setSubject(subject);
} catch (MessagingException e) {
e.printStackTrace();
}
// Envoie du mail
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(LOGIN_SMTP1, PASSWORD_SMTP1);
transport.sendMessage(message, new Address[] { new InternetAddress(receiver),
new InternetAddress(copyRecei) });
} catch (MessagingException e) {
e.printStackTrace();
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
Try using lesser secure settings in your gmail config
https://myaccount.google.com/intro/security

Java: How do I attach multiple files to an email?

I have a list of files that are created on application launch, and I want those files to be sent via email. The emails do send, but they don't have any attachments.
Here's the code:
private Multipart getAttachments() throws FileNotFoundException, MessagingException
{
File folder = new File(System.getProperty("user.dir"));
File[] fileList = folder.listFiles();
Multipart mp = new MimeMultipart("mixed");
for (File file : fileList)
{
// ext is valid, and correctly detects these files.
if (file.isFile() && StringFormatter.getFileExtension(file.getName()).equals("xls"))
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
messageBodyPart.setFileName(file.getName());
mp.addBodyPart(messageBodyPart);
}
}
return mp;
}
There's no error, warning, or anything else. I even tried creating a Multipart named childPart and assigning it to mp through .setParent(), and that did not work either.
I am assigning the attachments this way:
Message msg = new MimeMessage(session);
Multipart mp = getAttachments();
msg.setContent(mp); // Whether I set it here, or next-to-last, it never works.
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress("addressFrom"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("addressTo"));
msg.setSubject("Subject name");
msg.setText("Message here.");
Transport.send(msg);
How do I correctly send multiple attachments via Java?
This is my own email utility class, check if that the sendEmail method works for you
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
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.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {
public enum SendMethod{
HTTP, TLS, SSL
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public static boolean isValidEmail(String address){
return (address!=null && address.matches(EMAIL_PATTERN));
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public static boolean sendEmail(final String recipients, final String from,
final String subject, final String contents,final String[] attachments,
final String smtpserver, final String username, final String password, final SendMethod method) {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpserver);
Session session = null;
switch (method){
case HTTP:
if (username!=null) props.setProperty("mail.user", username);
if (password!=null) props.setProperty("mail.password", password);
session = Session.getDefaultInstance(props);
break;
case TLS:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
case SSL:
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.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
}
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, recipients);
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(contents, "text/html");
multipart.addBodyPart(bodypart);
if (attachments!=null){
for (int co=0; co<attachments.length; co++){
bodypart = new MimeBodyPart();
File file = new File(attachments[co]);
DataSource datasource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(datasource));
bodypart.setFileName(file.getName());
multipart.addBodyPart(bodypart);
}
}
message.setContent(multipart);
Transport.send(message);
} catch(MessagingException e){
e.printStackTrace();
return false;
}
return true;
}
}
you can create a zip file from your desired folder and then send it as a normal file.
public static void main(String[] args) throws IOException {
String to = "Your desired receiver email address ";
String from = "for example your GMAIL";
//Get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "Insert your password here");
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Write the subject");
String Final_ZIP = "C:\\Users\\Your Path\\Zipped.zip";
String FOLDER_TO_ZIP = "C:\\Users\\The folder path";
zip(FOLDER_TO_ZIP,Final_ZIP);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Write your text");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(Final_ZIP);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("ZippedFile.zip");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println(" Email has been sent successfully....");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
then the Zip Function is:
public static void zip( String srcPath, String zipFilePath) throws IOException {
Path zipFileCheck = Paths.get(zipFilePath);
if(Files.exists(zipFileCheck)) { // Attention here it is deleting the old file, if it already exists
Files.delete(zipFileCheck);
System.out.println("Deleted");
}
Path zipFile = Files.createFile(Paths.get(zipFilePath));
Path sourceDirPath = Paths.get(srcPath);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
Stream<Path> paths = Files.walk(sourceDirPath)) {
paths
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zipOutputStream.putNextEntry(zipEntry);
Files.copy(path, zipOutputStream);
zipOutputStream.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
System.out.println("Zip is created at : "+zipFile);
}

How to delete messages from specific sender in gmail using java

i want to delete messages from speicifc sender in my INBOX folder using java.
Here i found this code to get all emails from gmail.
How can i get the specific sender (sender#gmail.com) and delete it or move it to trash folder.
Thank you
Code:
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "myemail#gmail.com";// change accordingly
String password = "password";// change accordingly
check(host, mailStoreType, username, password);
}
}
Using Gmail's RESTful API this is possible
Users.messages: list to get the messages
and
Users.messages: trash to send to trash

Categories