JAVA Problems sending email in HTML format with embedded image - java

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+doxWKGz4J7zHYAYWXH2dnh7OyN0olBgoJbrXrc8duCzn0ATU+lxMTQ7M7A5b+T1I+n3KSy4K+UubrW7tUudHWbuLiBrq7J6MZPiJBpmpqv2rRXlZZHjI3B0NC14LNjnZx+pqe309I6eHlXrnE+h4iHyo+qy8ZxtJCUwLJmsYRGm2sbc2ZrwG5Spmw3jGh/rpw3eH+by6gAa2IxhmgCZXEAWGRgtW0uQDJmAAAF9ElEQVR4nO2Ya3uiZhCGESHhIAICi6JoZDHGeCrVZNVs0+22Tdttu///53RmOKhRs1F77e6HuT9ErpHAw7zzzDsoCAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAxzDo6Ffz0dD51vrGUfrSSp+N5Nv9YTdI9kfl+0Voqi/Bmpqhr1ysB3p3Asi6LYfCiVSuqNBwK9by0IsFq+77dSun+QwI97BTp6xtGlCTfwrZMFhu9Wnc7IJZ4e3KbY/CdSS6Vg6m0vsT6oZdzcd4/TN+p0Vq2TBQr6xDUMU4Hcye7DQ/PfT39NG7Z9L+jbJVjGysyIro+5QWzKsuGfLhAJtUoHF/fvEty+Xva8XQcPIa0F9fsjLp4o8Ozn6QOsCqSw+etvePvhPgNf2/BNEAQlElo/4tIXsijPz9XnzOAxRfF3tMdgn3+dGgiLrrvd4RsS+Hp/+yNZVG7PFZiQPrSvXdvbX/QGfNcu50f18vorb49YPy6KTnNF0TzDI8QC9TWfIElqv4sL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dRoL71QofmjWjkwyO1RtEBTTI2DQzYpQXHoBWUTLkwBg4PacNGcIOWL0LhZCwRBHr9XYENENKnCeLahqbXpiimkLCjdBjU0LGTEb4iSZ1UhiYqslFM0/RaMX5JQXz5IgvXjTXtp4dHTXt8hD85j1fAzxT4gIe/pN99uHqwgWiQdW7oyaIpLOem6S6ygT+ezWbrbQOWWF69VIHW3JBeRHF9y9Kt1zOc9rzilwasNxijrDC08pCDJxW3hweQXnx7shYXX2B2usNoml7X2+7NcZI4oweezxIHhLsDX44nCXpcPuZN5P+GpukDFg1HEhpEPpzgr8ClcrgJLyF9siwtvq6ibXAQlQ8NepjdUedbri+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=
DsoCAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAzDMAxzDo6Ffz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HVeDutBluL2te77Y1NhNpNPt/YbzA0xhLEx6XBl1=
RMILRKd5WQBEICxfgEfbAYY0muWr0IFXjPBF6XyAbODRp9uo6V+m8ysMtYSZ4ddMZ7Egh65IvsK=
ga0oJYEz3Dq25gMAoUbGLeez4ICtrr6MPVF2lDSWMODOdshUGA168lYL6lZBMiakqwFytB/Xt0D=
d3ivgMB7GwQ62wI98gNEplSERSzVSu8CeBCCAlq+dXP2MWu5IPy6aD+n8E4CgT0S6G1P0w0qQdg=
7sE2n+3C5rWarXQuigErwFpZvRCUo5c35FltLNjUI1MxE5bQKTK8GAofkgm2BQzUbZbyocAkJxM=
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);
}
}
}

Related

Java IMAP connection error javax.mail.AuthenticationFailedException: AUTHENTICATE failed

I am using below java program and configurations to read Inbox in outlook email, but could not succeed.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Address;
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.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import com.nexera.blustream.batch.constants.CommonConstants;
import com.nexera.blustream.batch.entity.SubscriberDetails;
public class EmailScanner {
private String protocol;
private String imapHost;
private String username;
private String password;
private String folderName;
private String excelFilePath;
Properties prop;
InputStream inputStream = null;
private static final Logger LOG = Logger.getLogger(EmailScanner.class);
public EmailScanner() {
try {
prop = new Properties();
String propFileName = "config.properties";
prop.load(EmailScanner.class.getClassLoader()
.getResourceAsStream(propFileName));
this.setProtocol(prop.getProperty("PROTOCOL"));
this.setImapHost(prop.getProperty("IMAP_HOST"));
this.setUsername(prop.getProperty("USERNAME"));
this.setPassword(prop.getProperty("PASSWORD"));
this.setFolderName(prop.getProperty("FOLDER_NAME"));
this.setExcelFilePath(prop.getProperty("EXCEL_PATH"));
} catch (Exception e) {
LOG.error("Exception: " + e);
}
}
/**
* configureEmail() - used to connect to mailbox using properties mentioned
* in config.properties.
* passes the control to fetchUnReadMails.
*/
public void configureEmail() {
LOG.info("Entering method : configureEmail");
// Download Attachment First
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", this.getProtocol());
properties.setProperty("mail.imap.partialfetch", "false");
properties.put("mail.mime.base64.ignoreerrors", "true");
properties.put("mail.imap.tls.enable", "true");
properties.put("mail.imap.auth.plain.disable", "true");
Folder inbox = null;
Store store = null;
Session session = null;
try {
LOG.info("Creating session for email with properties "
+ properties.getProperty("mail.store.protocol"));
session = Session.getDefaultInstance(properties, null);
store = session.getStore(this.getProtocol());
LOG.info("Checking if store is connected " + store.isConnected());
if (!store.isConnected()) {
LOG.info("Store not connected, connecting");
try {
store.connect(imapHost,993, username, password);
} catch (Exception ex) {
LOG.error("Exception caught while connecting : "
+ ex.getMessage());
}
} else {
LOG.info("Store already connected, reading emails");
}
LOG.info("Reading emails");
inbox = store.getFolder(folderName);
inbox.open(Folder.READ_WRITE);
LOG.info("Opening Inbox in readWrite");
fetchUnReadMails(inbox);
} catch (MessagingException e) {
LOG.error("Exception Thrown while reading mails : " + e);
} catch (Exception ex) {
LOG.error("Exception Thrown while reading mails : " + ex);
} finally {
if (inbox != null) {
if (inbox.isOpen())
try {
inbox.close(true);
} catch (MessagingException e) {
LOG.error("Exception Thrown " + e.getMessage());
}
}
if (store != null) {
if (store.isConnected())
try {
store.close();
} catch (MessagingException e) {
LOG.error(
"Unable to close the store " + e.getMessage());
}
}
}
LOG.info("Exiting method : configureEmail");
}
public static void main(String[] args) {
LOG.info("Starting Execution");
EmailScanner emailBatchJob = new EmailScanner();
emailBatchJob.configureEmail();
LOG.info("Finished Execution");
}
}
program is failing to connect to the server, exception is thrown at the below line
store.connect(imapHost,993, username, password);
# MAIL BOX DETAILS FOR READING
PROTOCOL=imap
IMAP_HOST=outlook.office365.com
USERNAME=subscriptions#test.com
PASSWORD=<password>
FOLDER_NAME=Inbox`
#Exception Thrown
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:708)
at javax.mail.Service.connect(Service.java:342)
at javax.mail.Service.connect(Service.java:222)
at javax.mail.Service.connect(Service.java:243)
at com.email.demo.RetrieveEmailsUsingIMAP.getEmails(RetrieveEmailsUsingIMAP.java:46)
at com.email.demo.RetrieveEmailsUsingIMAP.main(RetrieveEmailsUsingIMAP.java:241)
Your help is much appreciated!!!
Thanks
I have tried to change the protocol to imaps but didn't work.
Also, facing below error when I tried to do some other changes to the configurations
javax.mail.MessagingException: Connection dropped by server?;

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 ?

javamail isnt sending mail by gmail?

im trying to develop an android mailbox app which would send and receive emails.
but im having issue by sending mail on javamail.
here is the codes;
ComposeMail.Java
package app.mailbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.util.Log;
public class Composemail extends AppCompatActivity {
private String to;
private String subject;
private String message;
private String username;
private String password;
public void sendthemail(View view) {
EditText toarea, subjectarea,messagearea;;
toarea = (EditText) findViewById(R.id.et_to);
subjectarea = (EditText) findViewById(R.id.et_sub);
messagearea = (EditText) findViewById(R.id.et_text);
String to = toarea.getText().toString();
String subject = subjectarea.getText().toString();
String message = messagearea.getText().toString();
try {
GMailSender sender = new GMailSender(username, password);
sender.sendMail(subject, message, username, to);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_composemail);
username = Login.username;
password = Login.password;
}
}
GmailSender.java
package app.mailbox;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new app.mailbox.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
JSSE Provider
package app.mailbox;
import java.security.AccessController;
import java.security.Provider;
public final class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
im new to android development guys, i have no idea about why it isnt running, i also tryed debugging too but didnt find out anything.
https://www.tutorialspoint.com/javamail_api/javamail_api_gmail_smtp_server.htm
also can i use this tutorial for android javamail app? or its not for android?
and i need a solution about how i can add a google autherization i mean a checking system which will check if given email and password is exist as gmail account? and i want to do that at login screen?

How can I create run time entry for email and password in following code?

Following is the code of Main.java file.
package com.app.mail1;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity {
EditText to, from, message, subject;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
GMailSender sender = new GMailSender("rockstarjamunjuice#gmail.com", "jamunjuice");
sender.sendMail("This is Subject",
"This is Body",
"user#gmail.com",
"user#yahoo.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
Here is the code for GMailSender.java file
package com.app.mail1;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new com.provider.JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try{
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
}catch(Exception e){
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
Can I set the username and password at run time?
Can I make String to Editable?
Please help me if I can edit this code and set sender's email id and password at run time?
Howto convert String to Editable
Howto change username/password:
Add this to class:
public class Main extends Activity {
private static String password;
private static String username;
public static void setUsername(String user){
username = user;
}
public static void setPassword(String pass){
password = pass;
}
// ...................................
GMailSender sender = new GMailSender(username, password);
}
Then, you can change pass/name:
public class SomeClass {
Main.setUsername("SomeUser");
Main.setPassword("StrongPassword");
}
Or you can use Intent for transfer data (username/password) in Activity

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