I can't send email - java

I have an app which sends out an email at a time selected by the Timepicker. Everything works fine except for the email part.
Here is my code for the email class :
package com.example.myapplication;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import static com.example.myapplication.Pop_up.item;
import static com.example.myapplication.Pop_up.rad;
import static com.example.myapplication.Pop_up.rad1;
import static com.example.myapplication.Pop_up.rb1;
import static com.example.myapplication.Pop_up.s1;
import static com.example.myapplication.Pop_up.s3;
import static com.example.myapplication.Pop_up_2.message;
public class GMailSender extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public GMailSender() {
if (rb1 != null && rad.isChecked()){
message=s1;
}else if(rb1 != null && rad1.isChecked())
{
message=item;
}
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = "user.name#gmail.com"; // username
_pass = "userpass"; // password
_from = "user.name#gmail.com"; // email sent from
_subject = s3; // email subject
_body = message; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public GMailSender(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
// msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject=string;
}
// more of the getters and setters …..
}
Here is my code for sending the email:
GMailSender m = new GMailSender("user.name#gmail.com", "userpass");
String[] toArr = {s4,"name#gmail.oom"};
m.setTo(toArr);
m.setFrom("user.name#gmail.com");
m.setSubject(s3);
m.setBody(message);
try {
m.addAttachment(path);
if(m.send()) {
Toast.makeText(context, "Email was sent successfully :)", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Email was not sent :(", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(context, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
But for some reason I keep getting the toast "Email was not sent :(" . Where am I going wrong? Please help.

Moving the jpg file to my internal memory solved the problem.

Related

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?

Send html email from file with variables from java - java

I want to send an email with html markup text.
I want that my code gets the message from a file on my pc and I want to be able to use variables I have in my project.
so that my message comes up like: Hello [username]
and that [username] is a variable.
package com.email;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to = new String[1];
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public SendMail() {
_host = "smtp.live.com"; // default smtp server
_port = "587"; // default smtp port
_sport = "587"; // default socketfactory port
_user = "user#hotmail.com"; // username
_pass = "password"; // password
_from = "user#hotmail.com"; // email sent from
_subject = "Welcome to Ravenous!"; // email subject
_body = "<h2 style='font-style: normal;font-weight: 700;Margin-bottom: 0;Margin-top: 0;font-size: 24px;line-height: 32px;font-family: Open Sans,sans-serif;color: #44a8c7;text-align: center'>Welcome to Ravenous!</h2><p style='font-style: normal;font-weight: 400;Margin-bottom: 0;Margin-top: 16px;font-size: 15px;line-height: 24px;font-family: Open Sans,sans-serif;color: #60666d;text-align: center'>Hello, we hope that you enjoy your stay on Ravenous.</p>"; // email body
_to[0] = "";
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public SendMail(String to) {
this();
_user = "user#hotmail.com";
_pass = "password";
_to[0] = to;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(_body, "text/html; charset=utf-8");
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
// props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.starttls.enable", "true");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public String[] getTo() {
return _to;
}
public void setTo(String[] _to) {
this._to = _to;
}
public String getFrom() {
return _from;
}
public void setFrom(String _from) {
this._from = _from;
}
public String getSubject() {
return _subject;
}
public void setSubject(String _subject) {
this._subject = _subject;
}
// more of the getters and setters …..
}
So how would I get my html message from an html file and send it with some variables?
This is what my template file looks like:
package com.email;
import java.io.*;
import java.util.*;
import com.world.entity.impl.player.Player;
import freemarker.template.*;
public class Template {
public static String body;
public static void getTemplate() throws Exception {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDirectoryForTemplateLoading(new File("./data/templates/"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map<String, Object> root = new HashMap<String, Object>();
root.put("userName", SendMail._username);
Map<String, String> latest = new HashMap<String, String>();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
freemarker.template.Template temp = cfg.getTemplate("Welcome.ftl");
Writer out = new OutputStreamWriter(System.out);
body = out.toString();
temp.process(root, out);
}
}
Use a templating engine for this, I personally did this with freemarker.
It allows you to store a template alongside your program which you fill by using variables passed from your code.
Map root = new HashMap();
root.put("name", "John Doe");
...
Template temp = cfg.getTemplate("mymailtemplate.ftl");
...
In the template you simply write something like this:
<h1>Welcome ${name}!</h1>
There is a good example on the freemarker 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+doxWKGz4J7zHYAYWXH2dnh7OyN0olBgoJbrXrc8duCzn0ATU+lxMTQ7M7A5b+T1I+n3KSy4K+UubrW7tUudHWbuLiBrq7J6MZPiJBpmpqv2rRXlZZHjI3B0NC14LNjnZx+pqe309I6eHlXrnE+h4iHyo+qy8ZxtJCUwLJmsYRGm2sbc2ZrwG5Spmw3jGh/rpw3eH+by6gAa2IxhmgCZXEAWGRgtW0uQDJmAAAF9ElEQVR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jWCF5LRNt0wUGKLiV1SgnlRyJthTfbCW6F7hOpKRtxVScy6RklKgb8ZyqCrv8BpYb+vmjKrcVI9PAmNFVJJThq8Qy+aHH7HVeDutBluL2te77Y1NhNpNPt/YbzA0xhLEx6XBl1RMILRKd5WQBEICxfgEfbAYY0muWr0IFXjPBF6XyAbODRp9uo6V+m8ysMtYSZ4ddMZ7Egh65IvsKga0oJYEz3Dq25gMAoUbGLeez4ICtrr6MPVF2lDSWMODOdshUGA168lYL6lZBMiakqwFytB/Xt0Dd3ivgMB7GwQ62wI98gNEplSERSzVSu8CeBCCAlq+dXP2MWu5IPy6aD+n8E4CgT0S6G1P0w0qQdg7sE2n+3C5rWarXQuigErwFpZvRCUo5c35FltLNjUI1MxE5bQKTK8GAofkgm2BQzUbZbyocAkJxMobwoZSp40OZkoSGGICU6dWcEzKL1OlHbpz+vtTbILAbrQrEEeZdF5pq/kRClSjwXSABo/obMrQXGthx8qcig37/ZbAMxIoWAYILLdRoL71QofmjWjkwyO1RtEBTTI2DQzYpQXHoBWUTLkwBg4PacNGcIOWL0LhZCwRBHr9XYENENKnCeLahqbXpiimkLCjdBjU0LGTEb4iSZ1UhiYqslFM0/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,iVBORw0KGgoAA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iYqslFM0/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);
}
}
}

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

Categories

Resources