I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.
Please feel free to use the form below to contact me.
I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.
Please feel free to use the form below to contact me.
The Android SDK makes it very easy to send emails from an application, but unfortunately, that's only if you want to send them via the built-in mailing app. For most situations this works fine, but if you want to send something out and don't want any input/intervention from the user, it's not as easy.
In this article I'm going to show you how to send an email in the background without the user even knowing - the application will do everything behind the scenes.
Before we begin, you'll need to download a few files via the link below - this is a special version of the JavaMail API, which was written specifically for Android.
http://code.google.com/p/javamail-android/downloads/list
I'll be walking you through a Mail wrapper that I wrote, which makes it much easier to send emails and even add attachments if that's something you'd like to do.
Here is the full wrapper class below, which I'll go through step by step - keeping in mind that you'll have to add the fore-said files if you want this to work. Add them as external libraries - they need to be accessible by the Mail class.
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
// more of the getters and setters …..
}
And now I'm going to go through each bit of code
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
In this piece of code we initialise the properties, and setup the default values.
Also, we're setting up the mime types for javamail. I've also added a comment which describes why we need this.
And you've probably noticed that there are 2 constructors - one overrides the other, just incase the you want to pass the username and password when instantiating the class.
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
This is the most important method - here we're putting all the data from the properties and sending the mail.
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
You can call this method at any time if you want to add an attachment, but make sure you call it before the send method.
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;
}
Here we're setting up the properties for the mail retrieval - defaulting to SMTP authentication.
Also keep in mind that this is all defaulted to connect to the Gmail (Google) SMTP server.
Below is an example of how to use the Mail wrapper, in an Android activity.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("gmailusername@gmail.com", "password");
String[] toArr = {"bla@bla.com", "lala@lala.com"};
m.setTo(toArr);
m.setFrom("wooo@wooo.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
}
25 foot drop, just so she can be a youtube sensation.
My apple ipad is now destroyed and she has 83 views.
I know this is totally off topic but I had to share it with someone!
in exchange for a link back to mine. Please blast me an
e-mail if interested. Kudos!
that you shared this useful info with us. Please stay us up to date like this.
Thanks for sharing.
He was entirely right. This submit truly made my day.
You can not consider just how much time I had spent for this info!
Thanks!
a lot more attention. I'll probably be returning to read more, thanks for the information!
this I really think I am going to be wanted to have a go because I have just about given up hope.
I saw that Dr Oz remarked about some products including 7keto
and kinda hope this functions at the same time.
It's the little changes that produce the most significant changes. Thanks a lot for sharing!
I am no longer positive whether this publish is written by way of him as nobody else recognise such designated about my trouble.
You are wonderful! Thanks!
I needs to spend some time learning more or understanding more.
Thank you for fantastic info I was searching for this information for my
mission.
Do you ever run into any internet browser compatibility problems?
A number of my blog readers have complained about my blog not operating correctly in
Explorer but looks great in Chrome. Do you have any tips to help fix this problem?
As a result of the later years atmosphere it their staying an increasingly to completely enable it to be inside
and out of each of the play vehicles. I remember back when I must
have been a younger kid and might revolve
appreciate the fulfilling ticket processing through my lead several I required accomplish is
film down the window. But this was in that case your is currently, I am just an older
man over the age of 70 there is certainly my legs beginning to hand out its high less excitement pushing an automatic automobile given that it
were enjoy a stunning hands-on 1. I are Aware Of technology presently has gotten beyond control and
really beginning increase making it to certainly man that could change anywhere close to as quickly
as a a woman who commuting a complete computerized bringing adjust.
I understand that in formal one and mascara utilize
automatics finally.
I americium not to imply it's just not entertaining, however its vigorously to release enjoyable tension there is by driving on the extremity and getting the velocity extract an individual your support. Or during the time you would hit a turn and possess those 3g turns and choose stuck high while endeavoring to change your assailant. Oh home buying when I used to race, I identify I can certainly still perform a many things therefore effective rejoice pertains well offer.
When I was young we didn't suitable stuff men accomplish nowadays and while you can smash this offend very it would be easiest keen to accept.
This create consumers wondering why they were racing.
Actually it was subsequently safer to make for many people or
should aim to haul activities than it has been into fly.
Racing have not actually been a considerable expenses vendor now for
the runners till now.
A single solution which controlled me as I show arrived aged is my effect
time is not near what it was formerly. For some reason does make
a person not need test and do lots of things after having
that occur nevertheless its something you observe medicine running roughly in great vehicles and dreaming about individuals to look.
Maybe someday I can start paying some games, I found a few sites that where cool
that can be played some auto racing sports however it would not everything I
decided it would. Quite I need for an Xbox or even a Manufacturers and try
their sport games; I wont understand s not an equivalent pressuring buttons in lieu of noticing it
hit you all through face.
But what you going to do? You should only live when and might besides get the most from it simply be secure though I will tell you that there's rarely far too much protective particularly if we are going fine over hundred cientos per day or perhaps in 60 minutes.
It's a matter I most likely to be actively looking to get more motivated in investigating, meaning that your post helps me a decent amount!
websites? I have a blog centered on the same subjects you discuss and would really like to
have you share some stories/information. I know my subscribers
would appreciate your work. If you're even remotely interested, feel free to shoot me an e-mail.
here. I did however expertise a few technical issues using this web
site, since I experienced to reload the web
site a lot of times previous to I could get it to load correctly.
I had been wondering if your web hosting is OK?
Not that I am complaining, but sluggish loading
instances times will often affect your placement in google and could damage your quality score if advertising and marketing with Adwords.
Well I'm adding this RSS to my e-mail and could look out for a lot more of your respective exciting content. Make sure you update this again soon.
you make running a blog look easy. The overall look of
your site is wonderful, let alone the content!
This post actually made my day. You cann't believe just how much time I had spent for this info! Thank you!
the usual info a person provide on your visitors? Is gonna be back regularly in order to inspect new posts
at this website is genuinely nice.
with this blog. Standing ovation!
You have touched some fastidious things here. Any way keep up wrinting.
as well glad to share my familiarity here
with friends.
I’ll be sure to bookmark it and come back to read more
of your useful info. Thanks for the post. I’ll
definitely return.
I have a blog based on the same topics you discuss and would love to have you share
some stories/information. I know my audience would appreciate your work.
If you are even remotely interested, feel free to shoot me an email.
m.setTo(toArr);
m.setFrom("wooo@wooo.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
please help
What does this exception "NetworkOnMainThreadException" mean?
Thank you for publishing this code.
i got this error pleas help :
01-11 13:48:59.818: E/MailApp(29958): Could not send email
01-11 13:48:59.818: E/MailApp(29958): android.os.NetworkOnMainThreadException
01-11 13:48:59.818: E/MailApp(29958): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.getLocalHost(InetAddress.java:371)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.Transport.send(Transport.java:117)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Mail.send(Mail.java:125)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Add$1.onClick(Add.java:58)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View.performClick(View.java:3480)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View$PerformClick.run(View.java:13983)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.handleCallback(Handler.java:605)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Looper.loop(Looper.java:137)
01-11 13:48:59.818: E/MailApp(29958): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-11 13:48:59.818: E/MailApp(29958): at dalvik.system.NativeStart.main(Native Method)
the opportunity, Guess I'll just book mark this web site.
I have something to contribute to the conversation.
Usually it is a result of the fire displayed in the article I browsed.
And on this article Sending Emails without User Intervention (no Intents) in Android. I was excited enough to drop a thought ;-) I do have a couple of questions for you
if it's okay. Could it be simply me or does it appear like some of these remarks come across like written by brain dead visitors? :-P And, if you are posting on additional online sites, I'd
like to keep up with you. Could you list the complete urls of all your public
pages like your linkedin profile, Facebook page or twitter feed?
I was interested to know how you center yourself and clear your head
prior to writing. I've had a hard time clearing my thoughts in getting my ideas out there. I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are wasted simply just trying to figure out how to begin. Any recommendations or hints? Kudos!
homework on this. And he in fact ordered me breakfast because I stumbled upon it for him.
.. lol. So allow me to reword this.... Thanks for the meal!
! But yeah, thanx for spending some time to talk about this subject
here on your web page.
wanted to say that I've really enjoyed surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope you write again very soon!
I mean, what you say is fundamental and everything. However imagine if you added some great
visuals or video clips to give your posts more, "pop"!
Your content is excellent but with pics and video
clips, this blog could certainly be one of
the most beneficial in its niche. Amazing blog!
So here is the deal: for SDK 9 and later, you have to put the code in a different thread than the UI thread. You can, for example, handle the code in an AsyncTask.
Another rude way to overcome the problem is to add the following code before using the Mail. But I truly don't recommend it.
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Your code has worked fine for me including attachments to the email. The only small problem I see is that the name of the attachments are based on the source file full pathname which is certainly too long. The file name would have been sufficient I think. Going to see if I can fix that in the source code provided...
Still, it is a great shoot. You have my thanks for this.
fahad alawam - January 11, 2012 @ 5:53 am. The android version concerned is 4.0.3 (SDK level 15).
This is a good piece of code. So is there a way to fix the problem? Some device settings to make in order to have the feature operate? A solution requiring android permissions of system level is fine with me.
net from PHP. I have always disliked the idea because of the costs.
But he's tryiong none the less. I've been using WordPress on
a number of websites for about a year and am nervous about switching to another platform.
I have heard good things about blogengine.net. Is there a way I can transfer
all my wordpress content into it? Any kind of help
would be really appreciated!
this post is actually a good piece of writing, keep
it up. Check out my website to get more info about car insurance in California, if you like.
articles for your blog in exchange for a link back to mine.
Please send me an email if interested. Kudos!
But the SDK level must be smaller than 9.
If not, the app will crashed because we are not allowed to do this...
But the SDK level must be
There's a lot of folks that I think would really enjoy your content. Please let me know. Many thanks
More exchange port info here: http://support.microsoft.com/kb/278339.
If you are having any connection issues ("Could not connect to SMTP host: xyz.mail.com Port: 25") - start your debugging process by commenting out the lines below in the _setProperties() function to disable the ssl negotiation.
//DISABLE SSL CONNECTION
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");
Also, make sure the value below is set to, "true"
props.put("mail.smtp.socketFactory.fallback", "true");
Cheers!
reading it, you could be a great author. I
will make sure to bookmark your blog and will eventually come back in the foreseeable future.
I want to encourage that you continue your great posts, have a nice weekend!
or Can you send me the zip file of your code??
actual effort to produce a really good article but what can I say I put things off a lot and don't seem to get anything done.
But if i want to use my own domain instead of gmail, what should i do?
Thanks again for the guideline.
really helpful..
:)
1. Make sure you add the items as JARs rather than External JARs. You do this by clicking the project, then selecting "Build Path", then selecting "Configure Build Path".
2. Make sure you check the box next to the JARs you just added. This is done under the "Order and Export" tab.
Also, make sure you add the following permission to your manifest file:
Unsupported action - That action is not currently supported
Please let me know how to solve it.
Here is my question : How can I receive mail with JavaMail Api or another Api on Android Project. I have been trying for this, but I couldnt find any working code on Android Application. I hope you can give me an idea about this situation.
This is a great howto, the code is very easy to follow & understand! Thanks very much for posting it!
No enclosing instance of type MailApp is accessible. Must qualify the allocation with an enclosing instance of type MailApp (e.g. x.new A() where x is an instance of MailApp).
I am getting javax.mail.AuthenticationFailedException error. I have rechecked username, password and all seem to be correct. Can someone please give hint to resolve the javax.mail.AuthenticationFailedException exception?
Thanks.
ps: I have got the source code of the jar files now. Thanks.
Thanks for the useful work.
Is the source code for the three jar files namely "additionnal.jar, mail.jar, activation.jar" available? If yes can you please provide the link?
Thanks,
Ambi.
01-11 13:48:59.818: E/MailApp(29958): Could not send email
01-11 13:48:59.818: E/MailApp(29958): android.os.NetworkOnMainThreadException
01-11 13:48:59.818: E/MailApp(29958): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-11 13:48:59.818: E/MailApp(29958): at java.net.InetAddress.getLocalHost(InetAddress.java:371)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
01-11 13:48:59.818: E/MailApp(29958): at javax.mail.Transport.send(Transport.java:117)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Mail.send(Mail.java:125)
01-11 13:48:59.818: E/MailApp(29958): at com.fahadalawam.kwtresturant.Add$1.onClick(Add.java:58)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View.performClick(View.java:3480)
01-11 13:48:59.818: E/MailApp(29958): at android.view.View$PerformClick.run(View.java:13983)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.handleCallback(Handler.java:605)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Handler.dispatchMessage(Handler.java:92)
01-11 13:48:59.818: E/MailApp(29958): at android.os.Looper.loop(Looper.java:137)
01-11 13:48:59.818: E/MailApp(29958): at android.app.ActivityThread.main(ActivityThread.java:4340)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:48:59.818: E/MailApp(29958): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-11 13:48:59.818: E/MailApp(29958): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-11 13:48:59.818: E/MailApp(29958): at dalvik.system.NativeStart.main(Native Method)
I could not make this work for Microsoft Mail Exchange Server, any idea how to set up for Microsoft Exchange Server. thanks.
Also how does it recognizes the user's password. We are no where giving the password right? We are only giving From Email address.
Any help is much appreciated.
Tried with
Server name: podabc.outlook.com
Port: 587
Encryption method: TLS
but nothing worked.
thanks.
Thank you for providing this information, so far your site is the only site that has answered my question!
I'm new at programming in java, and I cant seem to figure out how to 'load' this files into eclipse so I can get this to work. I know this is the answer, implementing it is whats giving me difficulty.
Can you create a quick video and post it on youtube so we can see how you did this?
Thanks alot
Can you plz send the code in zip file on my email mail4satya@gmail.com. I am getting lots of errors in this.
Never helped anybody with knowhow. But im in shame today.
Cause I were forced to get Your help.
My project is saved!
Thank You,gentleman.
Never helped anybody with knowhow. But im in shame today.
Cause I were forced to get Your help.
My project is saved!
Thank You,gentleman.
SamGU.
javax.mail.MesagingException: Unknown SMTP host: smtp.gmail.com; nested exception is:
java.net.UnknownHostException: Host is unresolved: smtp.gmail.com:465
and not the new 2-step verification.
if someone have an idea how to make it work with 2-step verification it will be great
Thanks for the code is really great
javax.mail.MesagingException: Unknown SMTP host: smtp.gmail.com; nested exception is:
java.net.UnknownHostException: Host is unresolved: smtp.gmail.com:465
..."
Hi Carl, you should check permission in the manifest file. Perhaps you forgot add permission for accessing internet
But do you know , how can we check whether the mail sent is successful or failed?
please help me send with attachment.
please send me the .zip file
my email is indela447@gmail.com
But in Android1.6 It is forcefully closing the application.Any idea about this
Sending a regular e-mail without attachments works fine, but when I try to attach a jpg that is in my res/drawable folder, it errors out on the line:
// send email
Transport.send(msg);
The addAttachment code seemed to handle my filepath OK, but I don't know if my filepath is valid. Do you know what the absolute path is for a jpg in the res/drawable folder? I was trying this code:
String filepath = Uri.parse("android.resource://com.michaeljdougan.mikemail/" + R.drawable.e002_c).toString();
m.addAttachment(filepath);
And filepath looks like:
"android.resource://com.michaeljdougan.mikemail/20137496"
I've used similar code to attach a jpg using code for the built-in e-mail program, in a putExtra(EXTRA_STREAM statement, and it worked.
Do you know if you have to copy the attachments to the SD card before attaching to an email? I'm testing using the simulator, and there is no SD card in the simulator.
For those that say you can't do this with the simulator, it does send the e-mail fine, without an attachment, and I can even send an attachment using the built-in email program, as long as I've setup my e-mail client properties (smtp server etc).
Thanks in advance!
You need to use subversion to pull a copy of the source code. svn checkout http://android-sms.googlecode.com/svn/trunk/ android-sms-read-only
Shouldn't it be javeax.net.ssl.SSLSocketFactory??
Do I need to go to the JAR files to correct this? TIA.
Thanks for this post, really awesome.
For future reference, is there no way of adding the missing code back into the main post to save other people the trouble?
lol @ the users asking you to contact them personally via email with a solution to their problem
perfect tutorial, works very well! Thanks alot for that!
But: I tried to add a bcc recipient, which doesnt work. Instead, a copy to the _to recipient is send twice. I used a similiar code as for adding recipients in mail.java.
Do you know a solution?
Thanks very much for this code!!
I think that it doesn't suppose to work on an emulator, only on a real device.
Try checking it on your phone.
Good luck, Elad
I was wondering are you trying this from an actual phone or are you using the emulator?
But isn't it bit risky to put your password? someone can easily decompile the apk.. Any suggestions?
Thanks
23:18:00.703 904 ERROR dalvikvm Could not find class 'org.me.emailtestandroid.Mail', referenced from method org.me.emailtestandroid.MainActivity$1.onClick
23:18:11.974 904 ERROR AndroidRuntime FATAL EXCEPTION: main
23:18:11.974 904 ERROR AndroidRuntime at org.me.emailtestandroid.MainActivity$1.onClick(MainActivity.java:33)
23:18:11.974 904 ERROR AndroidRuntime at android.view.View.performClick(View.java:2485)
23:18:11.974 904 ERROR AndroidRuntime at android.view.View$PerformClick.run(View.java:9080)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Handler.handleCallback(Handler.java:587)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Handler.dispatchMessage(Handler.java:92)
23:18:11.974 904 ERROR AndroidRuntime at android.os.Looper.loop(Looper.java:123)
23:18:11.974 904 ERROR AndroidRuntime at android.app.ActivityThread.main(ActivityThread.java:3683)
23:18:11.974 904 ERROR AndroidRuntime at java.lang.reflect.Method.invokeNative(Native Method)
23:18:11.974 904 ERROR AndroidRuntime at java.lang.reflect.Method.invoke(Method.java:507)
23:18:11.974 904 ERROR AndroidRuntime at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
23:18:11.974 904 ERROR AndroidRuntime at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
23:18:11.974 904 ERROR AndroidRuntime at dalvik.system.NativeStart.main(Native Method)
Thanks alot!!
Thanx
thx
The problem is Eclipse screw up for reference jar. After change .classpath .. able to send mail already..
java.lang.NoClassDefFoundError
how do I solve ?
..praveenkanade@yahoo.com
i am trying to do this ,but there is nothing showing (the project is running well,there is no error)..i have done every thing ,like completed uses-permission,and have write extra methods(setFrom,setSubject etc)...but my project is not showing anything ...its only showing a button and also its not showing the Toast materials...please someone help me...its very important for me.
advance thanks,
Manoj
Mail m = new Mail("myusername@gmail.com", "mypassword");
I get this error any ideas :
jar:
Result: -1
pkg: /data/local/tmp/AutomatedEmail.apk
Success
33 KB/s (6951 bytes in 0.204s)
About to start org.me.automatedemail/org.me.automatedemail.AutoEmail
DDM dispatch reg wait timeout
Can't dispatch DDM chunk 52454151: no handler defined
Can't dispatch DDM chunk 48454c4f: no handler defined
Starting: Intent { cmp=org.me.automatedemail/.AutoEmail }
run:
BUILD SUCCESSFUL (total time: 48 seconds)
thank u.......
worked in the first go.
can send me the zip project file??
thankss.
thanks in advance!!!!!
please help
thanks in advance
Any Ideas? I want to use my own mail server. Please contact back via email.
It giving me SMTP Exception.
Can you please send the code my Email.
Thank you
Good Work!!
Can you plz send the code in zip file on my email deepanshu.wad@gmail.com.
Bcz i am getting errors in this.
I am in urgent need plz help!!
Thank you;)
Is there any way to avoid having to specify the sending password, maybe by using AccountManager to authenticate with the phone's gmail account?
Again may thanks.
*hug*
I first ran into a "Untrusted Certificate" issue (due to my self signed cert) that I had to resolve by adding this to my code
static {
Security.addProvider(new JSSEProviderHarmony());
}
with:
public final class JSSEProviderHarmony extends Provider {
public JSSEProviderHarmony() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction() {
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;
}
});
}
}
and had to add a "TrustAllSSLFactory" by
replacing
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
with
props.setProperty("mail.smtp.socketFactory.class", "com.ur.app.TrustAllSSLSocketFactory");
at ur method setProperties().
public class TrustAllSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;
public TrustAllSSLSocketFactory() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null,
new TrustManager[] { new TrustAllTrustManager()},
null);
factory = (SSLSocketFactory)sslcontext.getSocketFactory();
} catch(Exception ex) {
// ignore
}
}
public static SocketFactory getDefault() {
return new TrustAllSSLSocketFactory();
}
@Override
public Socket createSocket(Socket socket, String s, int i, boolean flag)
throws IOException {
return factory.createSocket(socket, s, i, flag);
}
@Override
public Socket createSocket(InetAddress inaddr, int i,
InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
}
@Override
public Socket createSocket(InetAddress inaddr, int i)
throws IOException {
return factory.createSocket(inaddr, i);
}
@Override
public Socket createSocket(String s, int i, InetAddress inaddr, int j)
throws IOException {
return factory.createSocket(s, i, inaddr, j);
}
@Override
public Socket createSocket(String s, int i) throws IOException {
return factory.createSocket(s, i);
}
@Override
public Socket createSocket( ) throws IOException {
//log.debug( "createSocket 0");
return factory.createSocket();
}
@Override
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
On the server side the default postfix master.cf file has to have enabled smtps with
smtpd_tls_wrappermode=yes
smtpd_sasl_auth_enable=yes
to prevent:
java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:604 0xaf076228:0x00000000)
Can anyone hele me regarding the same.
I must suggest one thing to anyone having trouble getting this to work: you must add the XML tag to your AndroidManifest.xml file. It took me several hours to figure this out. Also took before I realized that to set this in Eclipse, don't just type INTERNET; type android.permission.INTERNET. (Also once I got it working, the message I sent landed in Spam.)
@Reza Nezami
You can make this send HTML content by replacing this bit of the 'send()' method:
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
with
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(_body, "text/html");
_multipart.addBodyPart(messageBodyPart);
You could obviously make the mime type here a parameter that you pass into setBody().
09-28 15:42:26.382: ERROR/MailApp(4363): javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
09-28 15:42:26.382: ERROR/MailApp(4363): nested exception is:
09-28 15:42:26.382: ERROR/MailApp(4363): java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
09-28 15:42:26.382: ERROR/MailApp(4363): error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:585 0xaf589f78:0x00000000)
Any help please?
thx
public void setTo(String[] toArr) {
this._to = toArr;
}
public void setFrom(String string) {
this._from = string;
}
public void setSubject(String string) {
this._subject = string;
}
Thank you!