I'm trying to send emails with java from database. After I run my main method for some reason I'm getting this error:
Exception in thread "main" javax.mail.internet.AddressException: Illegal semicolon, not in group in string ``john#gmail.com;eric#gmail.com;carrie#gmail.com;mark#gmail.com;britney#gmail.com'' at position 23
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:929)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:638)
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:615)
at EmailSender.sendEmail(TestSendEmails.java:120)
at EmailSender.sendEmail(TestSendEmails.java:128)
at Main.main(Main.java:8)
I'm assuming that my array list is built wrong. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestSendEmails {
private String emailTo;
private String emailSubject;
private String emailBody;
private String emailAttachments;
public TestSendEmails(){
}
public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments){
super();
this.emailTo = emailTo;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.emailAttachments = emailAttachments;
}
public String getEmailTo(){
return emailTo;
}
public void setEmailTo(String emailTo){
this.emailTo = emailTo;
}
public String getEmailSubject(){
return emailSubject;
}
public void setEmailSubject(String emailSubject){
this.emailSubject = emailSubject;
}
public String getEmailBody(){
return emailBody;
}
public void setEmailBody(String emailBody){
this.emailBody = emailBody;
}
public String getEmailAttachments(){
return emailAttachments;
}
public void setEmailAttachments(String emailAttachments){
this.emailAttachments = emailAttachments;
}
}
class TestSendEmailD{
private Connection con;
private static final String GET_EMAILS = "Select * From Emails";
private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://100.000.000.00\\SQLEXPRESS:3333;databaseName=dEmails;user=sys;password=admin");
}
public List<TestSendEmails> getTestSendEmails() throws Exception{
connect();
PreparedStatement ps = con.prepareStatement(GET_EMAILS);
ResultSet rs = ps.executeQuery();
List<TestSendEmails> result = new ArrayList<TestSendEmails>();
while(rs.next()){
result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments")));
}
disconnect();
return result;
}
private void disconnect() throws SQLException{
if(con != null){
con.close();
}
}
}
class EmailSender{
private Session session;
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.000.000.00");
props.put("mail.smtp.port", "123");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("work#gmail.comg", "1234");
}
});
}
public void sendEmail(TestSendEmails s) throws MessagingException{
init();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("work#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo()));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
Transport.send(message);
}
public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
for(TestSendEmails TestSendEmails:emails ){
sendEmail(TestSendEmails);
}
}
}
here is my main.java:
public class Main {
public static void main(String[] args) throws Exception {
TestSendEmailD dao=new TestSendEmailD();
List<TestSendEmails> list=dao.getTestSendEmails();
EmailSender sender=new EmailSender();
sender.sendEmail(list);
}
}
Can anyone help with this? Thanks in advance.
By default it parse with comma(,) separated email addresses and not with semicolon (;),
InternetAddress[] parse = InternetAddress.parse("abc#gmail.com,pqr#gmail.com");
System.out.println(parse[0].getAddress());
OUTPUT:
abc#gmail.com
Related
I am trying to display an arraylist in a JSP. I can query and display some of the elements in my model object, PoststackModel, but some of arraylist elements throw an error. In particular, I cannot display 'uniquedataid'. I do not understand why. Hope someone can help.
In my JSP, I can loop through some of the elements. This works:
<c:forEach var="input" items="${listInput}" >
${input.dataname},
${input.dataid},
${input.surveyname},
${input.surveyid},
${input.projectname},
${input.projectid},
${input.comments}<br>
</c:forEach>
But when I add 'uniquedataid', as such:
<c:forEach var="input" items="${listInput}" >
${input.uniquedataid},
${input.dataname},
${input.dataid},
${input.surveyname},
${input.surveyid},
${input.projectname},
${input.projectid},
${input.comments}<br>
</c:forEach>
I get the following error:
org.apache.jasper.JasperException: An exception occurred processing [/JSP/Viewers/Viewer_2D_Tabs_8.jsp] at line [114]
111: -->
112:
113: <c:forEach var="input" items="${listInput}" >
114: ${input.uniquedataid},
115: ${input.dataname},
116: ${input.dataid},
117: ${input.surveyname},
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:514)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.luminajio.viewers.Call_2DView.doGet(Call_2DView.java:47)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
javax.el.PropertyNotFoundException: Property [uniquedataid] not found on type [com.luminajio.input.poststack.PoststackModel]
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:260)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:212)
javax.el.BeanELResolver.property(BeanELResolver.java:333)
javax.el.BeanELResolver.getValue(BeanELResolver.java:92)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:113)
org.apache.el.parser.AstValue.getValue(AstValue.java:169)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944)
org.apache.jsp.JSP.Viewers.Viewer_005f2D_005fTabs_005f8_jsp._jspx_meth_c_005fforEach_005f0(Viewer_005f2D_005fTabs_005f8_jsp.java:618)
org.apache.jsp.JSP.Viewers.Viewer_005f2D_005fTabs_005f8_jsp._jspService(Viewer_005f2D_005fTabs_005f8_jsp.java:288)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.luminajio.viewers.Call_2DView.doGet(Call_2DView.java:47)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My Data Model:
package com.luminajio.input.poststack;
public class PoststackModel {
private String uniquedataid;
private String uniquejobid;
private int dataid;
private String dataname;
private int projectid;
private String projectname;
private int surveyid;
private String surveyname;
private String dataformat;
private String comments;
public PoststackModel(String uniquedataid, String uniquejobid, int dataid, String dataname, int projectid,
String projectname, int surveyid, String surveyname, String dataformat, String comments) {
super();
this.uniquedataid = uniquedataid;
this.uniquejobid = uniquejobid;
this.dataid = dataid;
this.dataname = dataname;
this.projectid = projectid;
this.projectname = projectname;
this.surveyid = surveyid;
this.surveyname = surveyname;
this.dataformat = dataformat;
this.comments = comments;
}
public String getuniquedataId() {
return uniquedataid;
}
public void setuniquedataId(String uniquedataid) {
this.uniquedataid = uniquedataid;
}
public String getUniquejobId() {
return uniquejobid;
}
public void setuniquejobId(String uniquejobid) {
this.uniquejobid = uniquejobid;
}
public int getDataid() {
return dataid;
}
public void setDataid(int dataid) {
this.dataid = dataid;
}
public String getDataname() {
return dataname;
}
public void setDataname(String dataname) {
this.dataname = dataname;
}
public int getProjectid() {
return projectid;
}
public void setProjectid(int projectid) {
this.projectid = projectid;
}
public String getProjectname() {
return projectname;
}
public void setProjectname(String projectname) {
this.projectname = projectname;
}
public int getSurveyid() {
return surveyid;
}
public void setSurveyid(int surveyid) {
this.surveyid = surveyid;
}
public String getSurveyname() {
return surveyname;
}
public void setSurveyname(String surveyname) {
this.surveyname = surveyname;
}
public String getdataFormat() {
return dataformat;
}
public void setdataFormat(String dataformat) {
this.dataformat = dataformat;
}
public String getcomments() {
return comments;
}
public void setcomments(String comments) {
this.comments = comments;
}
}
My Data Access Object is:
package com.luminajio.input.poststack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.luminajio.jdbc.JDBC;
public class PoststackDao {
//String schema = "petrolex";
String schema = "data";
String databaseURL = JDBC.JDBCURL + schema + "?allowPublicKeyRetrieval=true&useSSL=false" ;
String DBlogin= "root";
String DBpass= "lumi123";
public List<PoststackModel> list(String Survey) throws SQLException {
List<PoststackModel> listInput = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (Connection connection = DriverManager.getConnection(databaseURL, DBlogin, DBpass)) {
//String sql = "SELECT * FROM data ORDER BY DataName";
String sql = "SELECT * FROM data where surveyname = '" + Survey + "' ORDER BY DataName";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
String uniquedataid = result.getString("uniquedataid");
String uniquejobid = result.getString("uniquejobid");
int dataid = result.getInt("dataid");
String dataname = result.getString("dataname");
int projectid = result.getInt("projectid");
String projectname = result.getString("projectname");
int surveyid = result.getInt("surveyid");
String surveyname = result.getString("surveyname");
String dataformat = result.getString("dataformat");
String comments = result.getString("comments");
PoststackModel input = new PoststackModel(uniquedataid, uniquejobid, dataid, dataname, projectid, projectname, surveyid, surveyname, dataformat, comments);
listInput.add(input);
}
} catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
return listInput;
}
}
The servlet that calls the JSP is:
package com.luminajio.viewers;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
//import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.luminajio.input.poststack.PoststackDao;
import com.luminajio.input.poststack.PoststackModel;
import com.luminajio.jdbc.ConnectionFactory;
import com.luminajio.modules.Metadata;
import com.luminajio.modules.Notes;
import com.luminajio.modules.ParamOpts;
import com.luminajio.modules.Parameters;
import com.luminajio.modules.Rules;
public class Call_2DView extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String User = request.getParameter("User");
String Theme = request.getParameter("Theme");
String Survey = request.getParameter("Survey");
PoststackDao dao = new PoststackDao();
// Pass just the theme name 'darkness' rather than 'jquery-ui-darkness.css' (ThemeSubmit)
String ThemeSubmit = Theme.replace("jquery-ui-", "");
ThemeSubmit = ThemeSubmit.replace(".css", "");
try {
List<PoststackModel> listInput = dao.list(Survey);
request.setAttribute("listInput", listInput);
request.setAttribute("User",User);
request.setAttribute("Theme",Theme);
request.setAttribute("ThemeSubmit",ThemeSubmit);
request.setAttribute("Survey", Survey);
request.getRequestDispatcher("/JSP/Viewers/Viewer_2D_Tabs_8.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
throw new ServletException(e);
}
}
}
Any idea why I get an error when trying to display 'uniquedataid' in my JSP?
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 ?
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?
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+p0V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d3ivgMB7GwQ62wI98gNEplSERSzVSu8CeBCCAlq+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,iVBORw0KGgoAAAA=
NSUhEUgAAAKAAAACgCAMAAAC8EZcfAAAA7VBMVEX///90yW8IZGXp9uYAWlsAYWJRg4SNqqoAXl=
9wyGuzzs72/PVyo6QAU1QddHUAWVrs8vJtx2ef2Zz5/fkSbW7t+Oub2JjZ5+doxWKGz4J7zHYAY=
WXH2dnh7OyN0olBgoJbrXrc8duCzn0ATU+lxMTQ7M7A5b+T1I+n3KSy4K+UubrW7tUudHWbuLiB=
rq7J6MZPiJBpmpqv2rRXlZZHjI3B0NC14LNjnZx+pqe309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AMwzAMwzAMwzAMwzAMwzAMwzAMwzAM8z3xHzx=
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);
}
}
}
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