Sending Background Email IN Android Getting Exception - java

I am getting authentication Exception while sending Background Email .From last two days , I am searching and trying different things .but unable to solve . Please help me
Exception
02-12 12:59:22.093: W/System.err(7862): javax.mail.AuthenticationFailedException
02-12 12:59:22.093: W/System.err(7862): at javax.mail.Service.connect(Service.java:319)
02-12 12:59:22.093: W/System.err(7862): at javax.mail.Service.connect(Service.java:169)
02-12 12:59:22.093: W/System.err(7862): at javax.mail.Service.connect(Service.java:118)
02-12 12:59:22.093: W/System.err(7862): at javax.mail.Transport.send0(Transport.java:188)
02-12 12:59:22.093: W/System.err(7862): at javax.mail.Transport.send(Transport.java:118)
02-12 12:59:22.093: W/System.err(7862): at com.formdev.android.Mail.GMailSender.sendMail(GMailSender.java:102)
02-12 12:59:22.101: W/System.err(7862): at com.fromdev.android.androidqa.FeedbackActivity$4.run(FeedbackActivity.java:132)
02-12 12:59:22.101: W/System.err(7862): at java.lang.Thread.run(Thread.java:856)
GMailSender
public class GMailSender extends javax.mail.Authenticator {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private javax.mail.Session session;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
static {
Security.addProvider(new JSSProvider());
}
// ===========================================================
// Methods
// ===========================================================
public GMailSender(final String user, final 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 = javax.mail.Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);// Specify
// the
// Username
// and
// the
// PassWord
}
});
}
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) {
e.printStackTrace();
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
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");
}
}
}
JSSProvider
public class JSSProvider extends Provider {
public JSSProvider() {
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;
}
});
}
MainActivity
GMailSender sender = new GMailSender("sender, "password");
sender.sendMail(subject, message,
"sender","receiver");

May be this problem cause by Gmail account protection. Just click below link and disable security settings.It will work. https://www.google.com/settings/security/lesssecureapps

Related

I am unable to send email automatically from tab. However the same code works for mobile.. But not for tab

I dont know y i am unable to send mail from tab. It gives exception saying cud not communicate, network unreachable.
Gmailsender.java
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
private Multipart _multipart = new MimeMultipart();
static {
Security.addProvider(new 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");
props.setProperty("mail.smtp.ssl.enable", "true");
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);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(_multipart);
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) {
e.printStackTrace();
}
}
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");
}
}
}
I called this from activity as below.
GMailSender gMailSender=new GMailSender("user#abc.com","passwd");
gMailSender.sendMail(subject,message,"user#abc.com","to#abc.com");
Any suggestion wil be very helpful.

Sending mail from service using smtp

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.

how to send a email without user interaction in android?

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

Android sending email SocketTimeoutException

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

problem in sending mail in Java

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.

Categories