FolderClosedException while fetching from green mail server IMAP - java

I was testing green mail api and received following error while trying to fetch from green mail server though server was correctly up.
I am using green mail 1.4.1, java 8, java mail 1.5.3.
Below is the code that i have been executing and the exception that i am receiving.
package greenmailtest;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.user.UserException;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.ServerSetupTest;
public class ImapIT {
private static final String USER_PASSWORD = "abcdef123";
private static final String USER_NAME = "hascode";
private static final String EMAIL_USER_ADDRESS = "hascode#localhost";
private static final String EMAIL_TO = "someone#localhost.com";
private static final String EMAIL_SUBJECT = "Test E-Mail";
private static final String EMAIL_TEXT = "This is a test e-mail.";
private static final String LOCALHOST = "127.0.0.1";
private GreenMail mailServer;
public void setUp() {
mailServer = new GreenMail(ServerSetupTest.IMAP);
mailServer.start();
}
public void tearDown() {
mailServer.stop();
}
public void getMails() throws IOException, MessagingException,
UserException, InterruptedException {
// create user on mail server
GreenMailUser user = mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME,
USER_PASSWORD);
// create an e-mail message using javax.mail ..
MimeMessage message = new MimeMessage((Session) null);
message.setFrom(new InternetAddress(EMAIL_TO));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
EMAIL_USER_ADDRESS));
message.setSubject(EMAIL_SUBJECT);
message.setText(EMAIL_TEXT);
// use greenmail to store the message
user.deliver(message);
// fetch the e-mail via imap using javax.mail ..
Properties props = new Properties();
props.put("mail.store.protocol", "imap");
Session session = Session.getInstance(props);
Store store = session.getStore();
store.connect(ServerSetupTest.IMAP.getBindAddress(), ServerSetupTest.IMAP.getPort(), user.getLogin(),
user.getPassword());
// store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for (Message m : messages) {
System.out.println("*** Class: " + m.getClass() + " ***");
System.out.println("From: " + m.getFrom()[0]);
System.out.println("To: " + m.getRecipients(Message.RecipientType.TO)[0]);
System.out.println("Subject: " + m.getSubject());
System.out.println("Content: " + m.getContent());
}
folder.close(true);
// assertNotNull(messages);
// assertThat(1, equalTo(messages.length));
// assertEquals(EMAIL_SUBJECT, messages[0].getSubject());
// assertTrue(String.valueOf(messages[0].getContent())
// .contains(EMAIL_TEXT));
// assertEquals(EMAIL_TO, messages[0].getFrom()[0].toString());
}
public static void main(String[]args){
ImapIT imap=new ImapIT();
imap.setUp();
try {
imap.getMails();
imap.tearDown();
} catch (IOException | MessagingException | UserException
| InterruptedException e) {
e.printStackTrace();
}
}
}
javax.mail.FolderClosedException: * BYE JavaMail
Exception:java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1428)
at com.sun.mail.imap.IMAPMessage.getFrom(IMAPMessage.java:321)
at greenmailtest.ImapIT.getMails(ImapIT.java:75)
at greenmailtest.ImapIT.main(ImapIT.java:93)

Related

email receives duplicates from SPRING JAVA Mail APIs

I use Java mail APIs from a spring web application to send a weekly email to an outlook mail.
The feature was behaving normally for the first couple of weeks, then without any changes outlook received two emails, the next week three emails were received, then four, then five emails.
The logs set in the Java code indicates that only one email is being sent from the application.
I can't replicate the issue by changing the schedule to send each 15 minutes, or hour, or any shorter interval.
Email controller class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class WeeklyReportScheduler {
#Autowired
private WeeklyReportService weeklyReportService;
#Scheduled(cron = "${cron.expression}")
public void sendWeeklyReport(){
weeklyReportService.sendWeeklyReport();
}
}
Email service class:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Service
public class WeeklyReportService {
#Value("${weekly.report.mail.subject}")
private String subject;
#Value("${weekly.report.mail.body}")
private String mailBody;
#Value("${mail.body.empty.report}")
private String emptyReportMailBody;
#Value("${receiver}")
private String receiver;
#Autowired
private MailService mailService;
#Autowired
private WeeklyReportLogDao weeklyReportLogDao;
#Autowired
private ProjectService projectService;
#Value("${export.path}")
private String exportDir;
protected final Log logger = LogFactory.getLog(getClass());
public void sendWeeklyReport(){
boolean emptyReport = true;
//retrieving attachment data 'projects'
if(projects.size() != 0){
emptyReport = false;
}
String body = "";
if(emptyReport){
body = emptyReportMailBody;
} else {
body = mailBody;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/YYYY");
String dateString = format.format(new Date());
String mailSubject = subject + " " + dateString;
List recipients = new ArrayList<String>();
recipients.add(receiver);
String fileName = mailSubject.replace(" ", "_").replace("/", "_");
WeeklyReportExcelExport excelExport = new WeeklyReportExcelExport(exportDir, fileName);
excelExport.createReport(projects);
File excelFile = excelExport.saveToFile();
File[] attachments = new File[1];
attachments[0] = excelFile;
boolean sent = false;
String exceptionMessage = "";
for(int i=0; i<3; i++){
try {
logger.info("Sending Attempt: " + i+1);
Thread.sleep(10000);
mailService.mail(recipients, mailSubject, body, attachments);
sent = true;
break;
} catch (Exception ex) {
logger.info("sending failed because: " + ex.getMessage() + " \nRe-attempting in 10 seconds");
exceptionMessage = ex.getMessage();
sent = false;
}
}
if(!sent){
weeklyReportLogDao.logFailedReporting(dateString, exceptionMessage);
}
//re-try 3 times in case of mail sending failure
}
MailService class:
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailServiceImpl implements MailService {
/** The From address for the e-mail. read from ant build properties file */
private String fromAddress;
/** The mail sender. */
private JavaMailSender mailSender;
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public void mail(List<String> emailAddresses, String subject, String text, File[] attachments) throws MailException {
//System.out.println("mail: "+subject);
MimeMessage message = null;
// Fill in the From, To, and Subject fields.
try {
message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setFrom(fromAddress);
for (String emailAddress : emailAddresses) {
messageHelper.addTo(emailAddress);
}
messageHelper.setSubject(subject);
// Fill in the body with the message text, sending it in HTML format.
messageHelper.setText(text, true);
// Add any attachments to the message.
if ((attachments != null) && (attachments.length != 0)) {
for (File attachment : attachments) {
messageHelper.addAttachment(attachment.getName(), attachment);
}
}
}
catch(MessagingException mse) {
String warnMessage = "Error creating message.";
logger.warn(warnMessage);
throw (new RuntimeException(warnMessage, mse));
}
try {
mailSender.send(message);
} catch (Exception ex){
logger.info("Exception sending message: " + ex.getMessage());
}
}
}
you might have duplicate entries on your argument emailAddresses, try moving it to treeset if you cant ensure duplicate entries from the repository layer

How to correct Invalid Protocol: null sending mail and Could not to SMTP host: using javax.mail?

I have a problem, I am using slack and mail.
I have got a method to create a folder with header "chan", but it doesn't work:
method getMessage()
for (String chan : channels){
sentMessage(chan);//поменять куда вставить
System.out.println(chan);
Enter:
"Что то пошло не такjavax.mail.MessagingException: Could not to SMTP host: localhost, port 25; nested exception is : java.net.Connection refused connect"
If I comment out
sentMessage(chan);//поменять куда вставить
I have got send message from slack to mail.
This is my program on java.
package ru.slacks;
import com.github.seratch.jslack.*;
import com.github.seratch.jslack.api.methods.SlackApiException;
import com.github.seratch.jslack.api.methods.request.channels.ChannelsListRequest;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import com.github.seratch.jslack.api.methods.request.im.ImListRequest;
import com.ullink.slack.simpleslackapi.*;
import com.ullink.slack.simpleslackapi.SlackSession;
import com.ullink.slack.simpleslackapi.events.SlackMessagePosted;
import com.ullink.slack.simpleslackapi.impl.ChannelHistoryModuleFactory;
import static java.util.stream.Collectors.toList;
import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory;
import org.glassfish.grizzly.http.server.util.StringParser;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
public class SlackTools {
public SlackTools() throws IOException, SlackApiException {
}
private String token=".....our_token......";
static final Slack slack = Slack.getInstance();
List<String> channels = slack.methods().channelsList(ChannelsListRequest.builder().token(token).build())
.getChannels().stream().map(c -> c.getId()).collect(toList());
public void getChannels() throws IOException, SlackApiException {
System.out.println("---------------Channels---------------");
for (String chan : channels){
sentMessage(chan);//поменять куда вставить
System.out.println(chan);
}
}
public class EmailAuthenticator extends javax.mail.Authenticator
{
private String login;
private String password;
public EmailAuthenticator (final String login, final String password)
{
this.login = login;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(login, password);
}
}
public void sentMessage(String chanel) throws IOException {
Properties imap = new Properties();
imap.put("mail.debug" , "false" );
imap.put("mail.store.protocol" , "imaps" );//для доступа и обработки сообщений
imap.put("mail.imap.ssl.enable", true);
imap.put("mail.imap.port", 993);
Authenticator auth = new EmailAuthenticator("tm12018#yandex.ru",
"test123456");
Session session = Session.getDefaultInstance(imap, auth);
session.setDebug(false);
try {
Store store = session.getStore();
// Подключение к почтовому серверу
store.connect("imap.yandex.ru", "tm12018#yandex.ru", "test123456");
// Папка входящих сообщений
Folder inbox = store.getFolder(chanel);
if (!inbox.exists())
if (inbox.create(Folder.HOLDS_MESSAGES))
System.out.println("Folder was created successfully");
// Открываем папку в режиме только для чтения
//inbox.open(Folder.READ_ONLY);
inbox.open(Folder.READ_WRITE);
System.out.println("Количество сообщений : " +
String.valueOf(inbox.getMessageCount()));
if (inbox.getMessageCount() == 0)
return;
} catch (NoSuchProviderException e) {
System.err.println(e.getMessage());
} catch (MessagingException e) {
System.err.println(e.getMessage());
}
}
public void getMessage() throws IOException {
Properties p = new Properties();
p.put("mail.smtp.host", "smtp.yandex.ru");//протокол передачи сообщений, или smtp.gmail.com
p.put("mail.smtp.socketFactory.port", 465);
p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.auth", true);
p.put("mail.smtp.port", 465);
// p.put("mail.transport.protocol", "smtp");
Scanner in = new Scanner(System.in);
System.out.print("Enter your e-mail ");
String user = in.nextLine();
System.out.println("Enter your password");
String password = in.nextLine();
Session s = Session.getDefaultInstance(p,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, password);}});
System.out.print("Enter usernameto ");
String userto = in.nextLine();
for(String chan : channels ){
SlackSession sessiont = SlackSessionFactory.createWebSocketSlackSession(token);
sessiont.connect();
ChannelHistoryModule channelHistoryModule = ChannelHistoryModuleFactory.createChannelHistoryModule(sessiont);
List<SlackMessagePosted> messages = channelHistoryModule.fetchHistoryOfChannel(chan).stream().collect(toList());
System.out.println("---------------Messages- " + chan + "--------------");
for (SlackMessagePosted message : messages) {
System.out.println("E-mail:" + message.getUser().getUserMail() + ", message: " + message.getMessageContent() );
try {
Message mess = new MimeMessage(s);
mess.setFrom(new InternetAddress(user));
mess.setRecipients(Message.RecipientType.TO, InternetAddress.parse(userto));
mess.setSubject(message.getMessageContent().toString());
mess.setText(chan);
Transport.send(mess);
JOptionPane.showMessageDialog(null, "Письмо отправлено" );
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Что то пошло не так" + ex);
}
}
}
}
public static void main(String[] args) throws IOException, SlackApiException, MessagingException {
SlackTools sl = new SlackTools();
sl.getChannels();
sl.getMessage();
System.exit(0);
}
}
Looks like the response is telling you that there is no process (or at least not a email host) listening on your localhost port 25. Are you sure it's there? What happens when you do telnet localhost 25 ?

Using Javamail to get attachments

Good Morning,
I have been working on this project for a few days now and have ground to a halt. Downloading attachments seems to take forever and it would appear to be at the writing file to disk line. I have read about many options (FileChannel, bulk getContent and a few others but can not make this code execute at a reasonable rate) I am not to sure if the only bottle neck is the downloading of the files from O365 however I thought I would ask a question to see if somebody could review this code and hopefully tell me what I have done wrong. The goal of the application is to log into Exchange Online (o365) and download all attachments within a certain mail box. Please note that this code has been modified so many times to see if I could make performance increases by using threading and so on:
As I said I have shifted everything around a lot to try and make this work better so please don't blow me up for some of the code not making too much sense. I am not trying to get somebody else to finish this project, I am looking for guidance with a language that I do not have a great deal of experience with.
package o365connect;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
/**
*
* #author Charlie
*/
public class AttDownload extends Thread {
public static int Lower = 0;
public static int Upper = 0;
public static int Counter = 0;
public static Session session;
public static Store store;
public static Properties props = new Properties();
public static boolean fTest = false;
AttDownload(int i, int ii) {
Lower = i;
Upper = ii;
}
AttDownload() throws UnknownHostException {
super();
}
#Override
public void run() {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String pop3Host = "outlook.office365.com";
String mailStoreType = "imap";
String path = "Inbox/Scans to file";
String userName = "XXX#XXX.com";
String password = "XXXXXXX";
Folder emailFolder;
try {
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.host", "outlook.office365.com");
session = Session.getInstance(props);
int Size = functions.MBSize(pop3Host, userName, password, path);
System.out.println(Size);
store = session.getStore("imaps");
store.connect(pop3Host, userName, password);
emailFolder = store.getFolder(path);
emailFolder.open(Folder.READ_ONLY);
try {
Message[] messages;
messages = emailFolder.getMessages(Lower, Upper);
System.out.println("starting thread for - " + Lower + " - " + Upper);
int ASuc = receiveEmail(messages);
} catch (MessagingException | IOException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchProviderException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static int receiveEmail(Message messagesarr[]) throws IOException, MessagingException {
for (Message messagesarr1 : messagesarr) {
try {
Message message = messagesarr1;
Object content = message.getContent();
if (content instanceof String) {
} else if (content instanceof Multipart) {
Multipart multipart = (Multipart) message.getContent();
for (int k = 0; k < multipart.getCount(); k++) {
MimeBodyPart bodyPart = (MimeBodyPart) multipart.getBodyPart(k);
if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
long startTime = System.currentTimeMillis();
int ran = (int) startTime;
String fileName;
String fName = bodyPart.getFileName();
if (fName != null && !fName.isEmpty()) {
fileName = fName.replaceAll("\\s+", "");
} else {
continue;
}
if ("ATT00001.txt".equals(fileName)) {
continue;
} else {
System.out.println("starting copy of - " + fileName);
}
String destFilePath = "D:/Scans/";
bodyPart.saveFile(destFilePath + bodyPart.getFileName());
long stopTime = System.currentTimeMillis();
System.out.println("finished copying of - " + fileName + " - " + (stopTime - startTime) + " miliseconds.");
System.out.println(Counter);
Counter++;
} else {
}
}
}
}catch (MessagingException e) {
System.out.println(e);
}
}
return 1;
}
}
Functions.java
package o365connect;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import static o365connect.AttDownload.store;
/**
*
* #author Oliver
*/
public class functions {
public static int TestUser(String pop3host, String Username, String Password) throws NoSuchProviderException, MessagingException {
try {
Session session = Session.getInstance(AttDownload.props);
store = session.getStore("imaps");
store.connect(pop3host, Username, Password);
return 0;
} catch (MessagingException e) {
System.out.println(e + "User Name Invalid");
return 1;
}
}
public static Folder TestFolder(Store store, String Path) throws MessagingException {
Folder emailFolder;
emailFolder = store.getFolder(Path);
emailFolder.open(Folder.READ_ONLY);
AttDownload.fTest = true;
emailFolder.close(false);
return emailFolder;
}
public static int MBSize(String pop3Host, String userName, String password, String Path) {
int Size = 0;
Session session = Session.getInstance(AttDownload.props);
try {
Store store = session.getStore("imaps");
store.connect(pop3Host, userName, password);
Folder emailFolder = store.getFolder(Path);
emailFolder.open(Folder.READ_ONLY);
Size = emailFolder.getMessageCount();
emailFolder.close(false);
store.close();
return Size;
} catch (MessagingException e) {
System.out.println(e + "MBSize");
}
return Size;
}
}
O365Connect.java
package o365connect;
import java.io.IOException;
import javax.mail.MessagingException;
public class O365Connect {
public static void main(String[] args) throws IOException, MessagingException, InterruptedException {
MainScreen ms = new MainScreen();
ms.setVisible(true);
AttDownload dl = new AttDownload(1, 1000);
dl.start();
}
}
Edit:
props.put("mail.imaps.fetchsize", "819200");
props.put("mail.imaps.partialfetch", "false");
sped things up, 128 seconds down to 12 seconds to download a 7mb file.
fetchsize is not used if partialfetch is false; it will download the entire attachment in one request. As long as you have enough memory for the largest possible attachment, that's fine. Otherwise, leave partialfetch set to true (default) and set the fetchsize large enough to give reasonable performance without using excessive memory.
JavaMail properties are described in the javadocs, on the page for each protocol provider. For example, the IMAP provider properties are described on the com.sun.mail.imap package javadoc page.

JAVA Problems sending email in HTML format with embedded image

Hello guys i lost two hours to solve this problem.
I have a Java class that send mail and the body inside is in HTML format
here that method
private void sendMail() {
String body = "<html><body><p>Mr.<b>Jack Frusciante</b><br/>Work : <b>Programmer</b><br/><img alt=\"Firm\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAA7VBMVEX///90yW8IZGXp9uYAWlsAYWJRg4SNqqoAXl9wyGuzzs72/PVyo6QAU1QddHUAWVrs8vJtx2ef2Zz5/fkSbW7t+Oub2JjZ5+doxWKGz4J7zHYAYW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LyF9siwtvq6ibXAQlQ8NepjdUedbri+YQBvH40M/ILTGcXzujwsMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAM8z3xHzxMgUvIvKzHAAAAAElFTkSuQmCC\"/><br/><p>Lorem ipsum</p></p></body></html>";
SendMail sendMail = new SendMail("jack#gmail.com","othermail#gmail.com","subject","");
sendMail.setCC("othermailcc#gmail.com");
sendMail.setBody(body);
sendMail.send();
}
and here the SendMail class
package com.jack.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.PreencodedMimeBodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.mail.MailMessage;
import com.liferay.portal.kernel.mail.SMTPAccount;
import com.liferay.util.mail.MailEngine;
import com.sun.mail.smtp.SMTPMessage;
public class SendMail {
private String from;
private String subject;
private String body;
private String to;
private String cc;
private String cid;
private String smtpHost;
private String smtpPort;
private Boolean authenticationRequired;
private String authenticationUsername;
private String authenticationPassword;
public SendMail(String from,String to,String subject,String body) {
super();
this.to = to;
this.from = from;
this.subject = subject;
this.body = body;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpPort() {
return smtpPort;
}
public void setSmtpPort(String smtpPort) {
this.smtpPort = smtpPort;
}
public Boolean getAuthenticationRequired() {
return authenticationRequired;
}
public void setAuthenticationRequired(Boolean authenticationRequired) {
this.authenticationRequired = authenticationRequired;
}
public String getAuthenticationUsername() {
return authenticationUsername;
}
public void setAuthenticationUsername(String authenticationUsername) {
this.authenticationUsername = authenticationUsername;
}
public String getAuthenticationPassword() {
return authenticationPassword;
}
public void setAuthenticationPassword(String authenticationPassword) {
this.authenticationPassword = authenticationPassword;
}
public void setCC(String cc) {
this.cc=cc;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public void send() {
new Thread( new Runnable() {
#Override
public synchronized void run() {
performSend();
}
}).start();
}
private void performSend() {
try {
Session session = getSession();
SMTPMessage transport = new SMTPMessage(session);
InternetAddress iaFrom = new InternetAddress(from, from);
InternetAddress iaTo = new InternetAddress(to,to);
InternetAddress iaCC = (cc!=null) ? new InternetAddress(cc,cc) : null;
MimeMultipart mailMessage = new MimeMultipart("related");
BodyPart bp = new MimeBodyPart();
bp.setContent(body,"text/html");
mailMessage.addBodyPart(bp);
transport.setContent(mailMessage);
transport.setFrom(iaFrom);
if(iaCC!=null) {
transport.setRecipient(RecipientType.CC, iaCC);
}
transport.setSubject(subject);
InternetAddress[] recipients = { iaTo };
Transport.send(transport, recipients);
System.out.println("Sent message successfully....");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Session getSession() {
Properties mailProps = new Properties();
mailProps.put("mail.transport.protocol", "smtp");
mailProps.put("mail.smtp.host", "smtp.gmail.com");
mailProps.put("mail.smtp.socketFactory.port", "465");
mailProps.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
mailProps.put("mail.smtp.auth", "true" );
mailProps.put("mail.smtp.port","465");
return Session.getInstance(mailProps,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("jack","jackpassword");
}
});
}
}
the mail arrives but image at the of html is never showed . I noted , inspected the source of message, that img tag is changed like this
<img alt=3D"Firm" src=3D"data:image/png;base64,iVBORw0KGgoAAAA=
NSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAA7VBMVEX///90yW8IZGXp9uYAWlsAYWJRg4SNqqoAXl=
9wyGuzzs72/PVyo6QAU1QddHUAWVrs8vJtx2ef2Zz5/fkSbW7t+Oub2JjZ5+doxWKGz4J7zHYAY=
WXH2dnh7OyN0olBgoJbrXrc8duCzn0ATU+lxMTQ7M7A5b+T1I+n3KSy4K+UubrW7tUudHWbuLiB=
rq7J6MZPiJBpmpqv2rRXlZZHjI3B0NC14LNjnZx+pqe309I6eHlXrnE+h4iHyo+qy8ZxtJCUwLJ=
msYRGm2sbc2ZrwG5Spmw3jGh/rpw3eH+by6gAa2IxhmgCZXEAWGRgtW0uQDJmAAAF9ElEQVR4nO=
2Ya3uiZhCGESHhIAICi6JoZDHGeCrVZNVs0+22Tdttu///53RmOKhRs1F77e6HuT9ErpHAw7zzz=
DsoCAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAxzDo6Ffz0dD51vrGUfrSSp+N5Nv9YTdI9k=
fl+0Voqi/Bmpqhr1ysB3p3Asi6LYfCiVSuqNBwK9by0IsFq+77dSun+QwI97BTp6xtGlCTfwrZM=
Fhu9Wnc7IJZ4e3KbY/CdSS6Vg6m0vsT6oZdzcd4/TN+p0Vq2TBQr6xDUMU4Hcye7DQ/PfT39NG7=
Z9L+jbJVjGysyIro+5QWzKsuGfLhAJtUoHF/fvEty+Xva8XQcPIa0F9fsjLp4o8Ozn6QOsCqSw+=
etvePvhPgNf2/BNEAQlElo/4tIXsijPz9XnzOAxRfF3tMdgn3+dG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kgm2BQzUbZbyocAkJxM=
obwoZSp40OZkoSGGICU6dWcEzKL1OlHbpz+vtTbILAbrQrEEeZdF5pq/kRClSjwXSABo/obMrQX=
Gthx8qcig37/ZbAMxIoWAYILLdRoL71QofmjWjkwyO1RtEBTTI2DQzYpQXHoBWUTLkwBg4PacNG=
cIOWL0LhZCwRBHr9XYENENKnCeLahqbXpiimkLCjdBjU0LGTEb4iSZ1UhiYqslFM0/RaMX5JQXz=
5IgvXjTXtp4dHTXt8hD85j1fAzxT4gIe/pN99uHqwgWiQdW7oyaIpLOem6S6ygT+ezWbrbQOWWF=
69VIHW3JBeRHF9y9Kt1zOc9rzilwasNxijrDC08pCDJxW3hweQXnx7shYXX2B2usNoml7X2+7Nc=
ZI4oweezxIHhLsDX44nCXpcPuZN5P+GpukDFg1HEhpEPpzgr8ClcrgJLyF9siwtvq6ibXAQlQ8N=
epjdUedbri+YQBvH40M/ILTGcXzujwsMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAMwzAM8z3xHzx=
MgUvIvKzHAAAAAElFTkSuQmCC"/>
and the body part starts with
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Anybody have an idea to solve this?
Thanks in advance
I think there was some problem similar to "twice encoding"... or something like.
You should try to understand how body message is transformed, inside the steps of sending process.
A smart alternative, if the image is in your document library and it is pubblic accessible, is to provide the URL instead the full-image content inside your email body... this may help you to avoid several potential issues related to SMTP protocol and mail server loading.
As an alternative, I suggest you to save your image in an image server and include its reference in the message body. Of course this solution will work as long as the image is available in the specific server that you use.
As and example, I uploaded your image to Imgur server and here is a simpler version to send mail from java:
package stack;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail{
public static void main(String emailAddress){
String host = "smtp.gmail.com";
String from = "yourMail#gmail.com";
String subject = "Testing java mail";
String contentBody = "<html>\n" + "<body>\n"
+ "<p>Mr.<b>Jack Frusciante</b>\n"
+ "<br/>Work : <b>Programmer</b><br/>\n"
+ "<img src =\"http://imgur.com/81h91BL.png\"/>\n" + "<br/>\n"
+ "<p>Lorem ipsum</p></p>\n" + "</body>\n" + "</html>";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
try{
Session session = Session.getDefaultInstance(props, null);
InternetAddress to_address = new InternetAddress(emailAddress.toLowerCase());
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, to_address);
message.setSubject(subject);
message.setContent(contentBody, "text/html; charset=UTF-8");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "yourMail#gmail.com", "yourPassword");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("This notification was sent to : " + emailAddress +"");
}
catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}

deleting a email from gmail server with javamail api

import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3SSLStore;
import javax.mail.Session;
import javax.mail.Flags;
import javax.mail.Message;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
import javax.mail.internet.MimeMessage;
import java.io.FileOutputStream;
import java.io.File;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.net.URL;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.Store;
import javax.mail.Folder;
import java.util.Properties;
import javax.mail.URLName;
/**
* This class is responsible for deleting e-mails.
*
* #author Frank W. Zammetti.
*/public class deletemail {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "examplemail#gmail.com";
private static final String SMTP_AUTH_PWD = "examplepassword";
private Session session;
private POP3SSLStore store;
private String username;
private String password;
private POP3Folder folder;
URLName url;
public static void main(String[] args) throws Exception{
new deletemail().test();
}
public void test() throws Exception{
try{
Properties pop3props = new Properties();
//----------------------------------------------
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
username="examplemail#gmail.com";
password="examplepassword";
url = new URLName("pop3", "pop.gmail.com", 995, "", username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
folder = (POP3Folder) store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message message[] = folder.getMessages();
System.out.println(message.length);
for (int i=0, n=message.length; i<n; i++) {
message[i].setFlag(Flags.Flag.DELETED, true);
System.out.println("hello world");
}
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (folder != null) {
folder.close(true);
}
if (store != null) {
store.close();
}
} catch (Exception e) { }
}
}
}
let in first the in box contain 10 messages
message.length=10
after executing this program message.
length is get decresed to 0
but when i open my gmail account messaes
are still thereand they are not get deleted from the inbox
The problem is that GMail is not following IMAP convention of deleting emails.
According to https://javaee.github.io/javamail/FAQ#gmaildelete you have to:
Label message with flag [Gmail]/Trash,
Navigate to that label and set flag DELETED to true for that email,
Close folder (with expunge flag set to true).
Assuming that you have emails in array you have to do something like this:
Folder trashFolder = this.open("[Gmail]/Trash", true);
for (Message m : messages) {
m.getFolder().copyMessages(new Message[]{m}, trashFolder);
}
this.close(trashFolder, true);
trashFolder = this.open("[Gmail]/Trash", true);
for (Message m : trashFolder.getMessages()) {
m.setFlag(Flags.Flag.DELETED, true);
}
this.close(trashFolder, true);
This Gmail help page probably explains what's going on.

Categories

Resources