I have this android application that I want to send an email to the user once the user has successfully registered. I am not able to send the email, though. After I click "Submit" and Im redirected to the Home activity as a successfully logged in user, I wait for about 10 seconds and then a yellow error message appears in the logcat saying that mail has not been sent.
This is where I trigger sending the email:
public class Signup extends Activity implements OnUserCreatedListener {
#Override
public void onUserCreated(Integer userId) {
editor = sharedPrefs.edit();
editor.putBoolean("userLoggedInState", true);
editor.putInt("currentLoggedInUserId", userId);
editor.commit();
Intent signupSuccessHome = new Intent(getApplicationContext(), Home.class);
signupSuccessHome.putExtra("reqFrom", "signup");
startActivity(signupSuccessHome);
try {
new EmailSender(userEmail, Configurationz.Emailz.OFFICIAL_ADDRESS, Configurationz.Emailz.SUCCESSFUL_SIGNUP_SUBJECT, Configurationz.Emailz.SUCCESSFUL_SIGNUP_BODY(userName), null).execute();
} catch (Exception e) {
}
finish();
}
This is the EmailSender Utility Class
public class EmailSender extends AsyncTask<String, Void, Boolean> {
String to;
String from;
String subject;
String message;
String[] attachments;
Mail mail = new net.asdasd.utilities.Mail();
public EmailSender(String to, String from, String subject, String message, String[] attachments) {
super();
this.to = to;
this.from = from;
this.subject = subject;
this.message = message;
this.attachments = attachments;
}
#Override
protected Boolean doInBackground(String... params) {
if (subject != null && subject.length() > 0) {
mail.setSubject(subject);
} else {
mail.setSubject("Subject");
}
if (message != null && message.length() > 0) {
mail.setBody(message);
} else {
mail.setBody("Message");
}
mail.setTo(to);
mail.setFrom(from);
try {
return mail.send();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
This is the mail class:
package net.asdasd.utilities;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
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 net.shiftinpower.configuration.Configurationz;
public class Mail extends javax.mail.Authenticator {
public String user;
public String password;
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Multipart getMultipart() {
return multipart;
}
public void setMultipart(Multipart multipart) {
this.multipart = multipart;
}
public Mail() {
host = "smtp.googlemail.com"; // default smtp server
port = "465"; // default smtp port
sport = "465"; // default socketfactory port
user = Configurationz.Emailz.ASDASD_OFFICIAL_ADDRESS;
password = Configurationz.Emailz.ASDASD_OFFICIAL_PASSWORD;
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
multipart = new MimeMultipart();
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 boolean send() throws Exception {
Properties props = _setProperties();
if (!user.equals("") && !password.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);
}
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;
}
}
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;
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
// the getters and setters
public String getBody() {
return body;
}
public void setBody(String _body) {
this.body = _body;
}
}
This is the error message:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.googlemail.com, port: 465;
nested exception is:
java.net.SocketTimeoutException: Connection timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
at javax.mail.Transport.send(Transport.java:118)
at net.asdasd.utilities.Mail.send(Mail.java:120)
at net.asdasd.utilities.EmailSender.doInBackground(EmailSender.java:38)
at net.asdasd.utilities.EmailSender.doInBackground(EmailSender.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.net.SocketTimeoutException: Connection timed out
at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
at java.net.Socket.connect(Socket.java:1002)
at java.net.Socket.connect(Socket.java:945)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 15 more
And this is the previous version of the class (and it worked)
public class EmailSender {
public boolean sendEmail(String to, String from, String subject, String message, String[] attachements) throws Exception {
Mail mail = new net.shiftinpower.utilities.Mail();
if (subject != null && subject.length() > 0) {
mail.setSubject(subject);
} else {
mail.setSubject("Subject");
}
if (message != null && message.length() > 0) {
mail.setBody(message);
} else {
mail.setBody("Message");
}
mail.setTo(to);
mail.setFrom(from);
return mail.send();
}
}
I was also calling it in a different way:
In Signup.java:
private class sendVerificationEmail extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
emailSender.sendEmail(userEmail, Configurationz.Emailz.ASDASD_OFFICIAL_ADDRESS, Configurationz.Emailz.SUCCESSFUL_SIGNUP_SUBJECT, Configurationz.Emailz.SUCCESSFUL_SIGNUP_BODY(userName), null);
} catch (Exception e) {
}
return null;
}
}
class CreateUser extends AsyncTask<String, String, String> {
//blah blah
#Override
protected void onPostExecute(String result) {
ShowLoadingMessage.dismissDialog();
try {
new sendVerificationEmail().execute();
} catch (Exception e) {
}
super.onPostExecute(result);
}
I don't think that smtp.googlemail.com exists; please try smtp.gmail.com
Related
so I searched a lot to send an email throught my app, but without the user having to log in in an email app and send it himself. I would like to just let him write it in an editText and then just press a button and send it to me. So that's what I did: 2 classes for the mail thing, my activity which calls it, add the 3 libraries and the internet permission. What did I do wrong?
Here is where I call the email process :
private View.OnClickListener btnMode1Listener = new
View.OnClickListener() {
#Override
public void onClick(View v) {
suggestionText = entre_suggestion.getText().toString();
Log.i("SendMailActivity", "Send Button Clicked.");
String fromEmail = "fromEmail#gmail.com";
String fromPassword = "frompassword";
String toEmails = "toEmail#gmail.com";
List toEmailList = Arrays.asList(toEmails
.split("\\s*,\\s*"));
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = "Suggestion";
String emailBody = suggestionText;
new SendMailTask(suggestions.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
}
};
This is the first class "GMail":
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
public GMail(String fromEmail, String fromPassword,
List toEmailList, String emailSubject, String emailBody) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
for (Object toEmail : toEmailList) {
Log.i("GMail","toEmail: "+toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress((String) toEmail));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");// for a html email
// emailMessage.setText(emailBody);// for a text email
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
And this is the second class "SendMailtask":
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
#Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Sending email....");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
#Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
#Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
And finally, the 3 librairies I added:
compile files('libs/activation.jar')
compile files('libs/additionnal.jar')
compile files('libs/mail.jar')
So yeah, I searched a lot and didn't find how to debug it. I tried a lot of different ways but it never sent the email. I just want to be clear that I don't want to open the mail app, I want the email to be sent without the user having to do something.
package com.auto.smartautomates.smartautomates.Helpers;
import com.crashlytics.android.Crashlytics;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
/**
* Created by sardar.khan on 6/8/2017.
*/
public class MailService {
// public static final String MAIL_SERVER = "localhost";
private String toList;
private String ccList;
private String bccList;
private String subject;
final private static String SMTP_SERVER = "smtp.gmail.com";
private String from;
private String txtBody;
private String htmlBody;
private String replyToList;
private boolean authenticationRequired = false;
public MailService(String from, String toList, String subject, String txtBody, String htmlBody) {
this.txtBody = txtBody;
this.htmlBody = htmlBody;
this.subject = subject;
this.from = from;
this.toList = toList;
this.ccList = null;
this.bccList = null;
this.replyToList = null;
this.authenticationRequired = true;
}
public void sendAuthenticated() throws AddressException, MessagingException {
authenticationRequired = true;
send();
}
/**
* Send an e-mail
*
* #throws MessagingException
* #throws AddressException
*/
public void send() throws AddressException, MessagingException {
Properties props = new Properties();
// set the host smtp address
props.put("mail.smtp.host", SMTP_SERVER);
props.put("mail.user", from);
props.put("mail.smtp.starttls.enable", "true"); // needed for gmail
props.put("mail.smtp.auth", "true"); // needed for gmail
props.put("mail.smtp.port", "587"); // gmail smtp port 587 default gmail
/*Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mobile#mydomain.com", "mypassword");
}
};*/
Session session;
if (authenticationRequired) {
Authenticator auth = new SMTPAuthenticator();
props.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(props, auth);
} else {
session = Session.getDefaultInstance(props, null);
}
// get the default session
session.setDebug(true);
// create message
Message msg = new javax.mail.internet.MimeMessage(session);
// set from and to address
try {
msg.setFrom(new InternetAddress(from, from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)});
} catch (Exception e) {
Crashlytics.logException(e);
msg.setFrom(new InternetAddress(from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
}
// set send date
msg.setSentDate(Calendar.getInstance().getTime());
// parse the recipients TO address
java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ",");
int numberOfRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients];
int i = 0;
while (st.hasMoreTokens()) {
addressTo[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);
// parse the replyTo addresses
if (replyToList != null && !"".equals(replyToList)) {
st = new java.util.StringTokenizer(replyToList, ",");
int numberOfReplyTos = st.countTokens();
javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos];
i = 0;
while (st.hasMoreTokens()) {
addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
st.nextToken());
}
msg.setReplyTo(addressReplyTo);
}
// parse the recipients CC address
if (ccList != null && !"".equals(ccList)) {
st = new java.util.StringTokenizer(ccList, ",");
int numberOfCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
}
// parse the recipients BCC address
if (bccList != null && !"".equals(bccList)) {
st = new java.util.StringTokenizer(bccList, ",");
int numberOfBCCRecipients = st.countTokens();
javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients];
i = 0;
while (st.hasMoreTokens()) {
addressBCC[i++] = new javax.mail.internet.InternetAddress(st
.nextToken());
}
msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC);
}
// set header
msg.addHeader("X-Mailer", "MyAppMailer");
msg.addHeader("Precedence", "bulk");
// setting the subject and content type
msg.setSubject(subject);
Multipart mp = new MimeMultipart("related");
// set body message
MimeBodyPart bodyMsg = new MimeBodyPart();
bodyMsg.setText(txtBody, "iso-8859-1");
bodyMsg.setContent(htmlBody, "text/html");
mp.addBodyPart(bodyMsg);
msg.setContent(mp);
// send it
try {
javax.mail.Transport.send(msg);
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
}
}
/**
* SimpleAuthenticator is used to do simple authentication when the SMTP
* server requires it.
*/
private static class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "someEmail#gmail.com";
String password ="yourPassword";
return new PasswordAuthentication(username, password);
}
}
public String getToList() {
return toList;
}
public void setToList(String toList) {
this.toList = toList;
}
public String getCcList() {
return ccList;
}
public void setCcList(String ccList) {
this.ccList = ccList;
}
public String getBccList() {
return bccList;
}
public void setBccList(String bccList) {
this.bccList = bccList;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setFrom(String from) {
this.from = from;
}
public void setTxtBody(String body) {
this.txtBody = body;
}
public void setHtmlBody(String body) {
this.htmlBody = body;
}
public String getReplyToList() {
return replyToList;
}
public void setReplyToList(String replyToList) {
this.replyToList = replyToList;
}
public boolean isAuthenticationRequired() {
return authenticationRequired;
}
public void setAuthenticationRequired(boolean authenticationRequired) {
this.authenticationRequired = authenticationRequired;
}
}
In your account settings, allow smtp, and allow unsafe apps
I am using following code. But in the mail, I am getting the palin html tags only not output in table format. Please help me to get the output as table format in the mail
StringBuilder content = new StringBuilder();
content.append("<HTML>")
.append("<HEAD>")
.append("<TITLE>Welcome</TITLE>")
.append("</HEAD>")
// Start on the body
.append("<BODY>")
.append("<CENTER>")
.append("<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=70%>")
.append("<TR>")
.append("<TH style=\"padding:5px\">Subject</TH>")
.append("<TH style=\"padding:5px\">Grade</TH>")
.append("</TR>")
.append("<TR>")
.append("<TD>Mathmatics</TD>")
.append("<TD>A</TD>")
.append("</TR>")
.append("<TR>")
.append("<TD>SCEINECE</TD>")
.append("<TD>B</TD>")
.append("</TR>")
.append("</TABLE>")
.append("</CENTER>")
.append("</BODY></HTML>");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject, content.toString());
}
i have used javax mail. this will work
public class Main {
public static void main(String[] arg) {
StringBuilder MessageContent = new StringBuilder();
MessageContent.append("<HTML>")
.append("<HEAD>")
.append("<TITLE>Welcome</TITLE>")
.append("</HEAD>")
// Start on the body
.append("<BODY>")
.append("<CENTER>")
.append("<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=70%>")
.append("<TR>")
.append("<TH style=\"padding:5px\">Subject</TH>")
.append("<TH style=\"padding:5px\">Grade</TH>")
.append("</TR>")
.append("<TR>")
.append("<TD>Mathmatics</TD>")
.append("<TD>A</TD>")
.append("</TR>")
.append("<TR>")
.append("<TD>SCEINECE</TD>")
.append("<TD>B</TD>")
.append("</TR>")
.append("</TABLE>")
.append("</CENTER>")
.append("</BODY></HTML>");
MailParam mp = new MailParam();
mp.setUsername("....");
.....
Properties props = new Properties();
props.put("mail.smtp.auth", mailParam.getAuth());
props.put("mail.smtp.starttls.enable", mailParam.getStartls());
props.put("mail.smtp.host", mailParam.getHost());
props.put("mail.smtp.port", mailParam.getPort());
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
try {
messageBodyPart.setContent(MessageContent, "text/html; charset=utf-8");
//messageBodyPart.setText(MessageContent);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailParam.getUsername(), mailParam.getPwd());
}
});
// Sender's email ID needs to be mentioned
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.addHeader("Content-Transfer-Encoding", "quoted-printable");
// Set From: header field of the header.
message.setFrom(new InternetAddress("your_mail#yourdomain");
//message.setRecipients(Message.RecipientType.TO,recipientAddress);
message.setRecipients(Message.RecipientType.TO, "npsantost#libero.it");
// Set Subject: header field
message.setSubject("my subject");
// Send the actual HTML message, as big as you like
//message.setContent("<h1>This is actual message</h1>", "text/html");
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
MailParam class
public class MailParam {
private String username;
String pwd;
String auth;
String startls;
String host;
String port;
String from;
String replyto;
String logopath;
public String getAuth() {
return auth;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public String getPwd() {
return pwd;
}
public String getStartls() {
return startls;
}
public String getUsername() {
return username;
}
public String getFrom() {
return from;
}
public String getReplyto() {
return replyto;
}
public String getLogopath() {
return logopath;
}
public void setAuth(String val) {
auth = val;
}
public void setHost(String val) {
host = val;
}
public void setPort(String val) {
port = val;
}
public void setPwd(String val) {
pwd = val;
}
public void setStartls(String val) {
startls = val;
}
public void setUsername(String val) {
username = val;
}
public void setFrom(String val) {
from = val;
}
public void setReplyto(String val) {
replyto = val;
}
public void setLogoPath(String val) {
logopath = val;
}
}
Here is my Utility class code:
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
add this block in your Class EmailUtility
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
try {
messageBodyPart.setContent(message, "text/html; charset=utf-8");
//messageBodyPart.setText(MessageContent);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
then replace
msg.setText(message);
with
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setContent(multipart);
My app runs a service which sends and email, this must be transparent for the user, so I use javax.mail.
These are the classes I implement:
JSSEProvider.java
public final class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
#Override
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;
}
});
}
}
MailSender.java
public class MailSender extends javax.mail.Authenticator {
private final String mailhost = "smtp.gmail.com";
private final String user;
private final String password;
private final Session session;
static {
Security.addProvider(new JSSEProvider());
}
public MailSender(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.socketFactor.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
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);
}
public class ByteArrayDataSource implements DataSource {
private final 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;
}
#Override
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
#Override
public String getName() {
return "ByteArrayDataSource";
}
#Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
And finally, this is how I send the email from service:
private void sendEmail(String email) {
String from = "mymail#gmail.com";
String pass = "mypass";
String to = email;
String subject = getString(R.string.email_subject);
String body = text_i_want_to_send;
MailSender mail = new MailSender(from, pass);
try {
mail.sendMail(subject, body, from, to);
Log.d("EMAIL", "Email sent!");
} catch (Exception e) {
Log.d("EMAIL", "Error: " + e.getMessage());
}
}
Now, the problem is that, when it should send the email, I can see in the LogCat the exception refered to the catch statement, but it does not give any details, it just says:
EMAIL Error: null
Have to say that I have goten the JSSEProvider and the MailSender clases from the diferent tutorials around the net about using javax.mail to send mails using smtp.
So, I have no clue about what I'm doing wrong
EDIT --
I have chaught the exception, and it was related to doing network operation on the main thread. So I'm using now an AsyncTask and this part is solved.
But now, I have another exception, related to authentication this time. I have received an email in my email account telling that some has tried to access to my account (me) and that gmail has blocked it. So, how can I solve this authentication issue?
Can you add a catch for a NullPointerException?
(and add throw e).
I guess you have a null pointer somewhere and like this you can have more data.
Therefor it's a bad habit to catch "Exception" as everything will be caught.
I have already tried to send a mail,it run successfully without error, but mail is not send.
where is the bug? any one please fix this issue.
This is my code -
MailSenderActivity.java
public class MailSenderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button send = (Button) this.findViewById(R.id.mail);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GmailSender sender = new GmailSender("xxxx#gmail.com", "12345");
sender.sendMail("This is Subject",
"This is Body",
"xxxx#gmail.com",
"xxxx#gmail.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
}
}
GmailSender.java
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.bugtreat.email.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");
}
}
}
JSSEProvider.java
import java.security.AccessController;
import java.security.Provider;
#SuppressWarnings("serial")
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;
}
});
}
}
Thanks in Advance
Maybe your app can't access your google account and can't send the email due to your high account security level.
Have a look here
two exception comes in my program.......
cannot connect to the localhost ,port 25
connection refused
code of mail.java is ---
package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Mail {
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;
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 getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSmtpServ() {
return smtpServ;
}
public void setSmtpServ(String smtpServ) {
this.smtpServ = smtpServ;
}
public Exception sendMail(){
try
{
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","localhost");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(message);
// -- Set some other header information --
msg.setHeader("MyMail", "Java Mail Test");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent to"+to+" OK.");
return null;
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Exception "+ex);
return ex;
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "Java.Mail.CA#gmail.com";
String password = "javamail";
return new PasswordAuthentication(username, password);
}
}
}
so please tell me what to do & why these exception arises & how can i can mail using the java & localhost as host.
....................... thanks in advance.
Just follow this code; it is really useful to send email into java desktop and it works.
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main
{
public static void main(String[] args)
{
final String username = "your#gmail.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
try
{
String body = "Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receiver#gmail.com"));
message.setSubject("Testing Subject");
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);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Here is the code snippet to send email.
try {
String host = "yourHostName";
String from = "test#test.com";
String to[] = {"test123#test123.com"};
String subject = "Test";
String message = "Test";
Properties prop = System.getProperties();
prop.put("mail.smtp.host", host);
Session sess1 = Session.getInstance(prop, null);
MimeMessage msg = new MimeMessage(sess1);
msg.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
//Fill the message
msg.setText(message);
Transport.send(msg);
} catch (MessagingException me) {
me.printStackTrace();
}
What exceptions are you getting while sending emails? Are you sure your SMTP server is listening at default port 25? Are you able to manually send the email via Telnet? Also, turn off any firewall while testing this just to be sure.