Created
June 29, 2017 13:34
-
-
Save chris-carneiro/a1d8361ba99634f5c1cdb136856b9671 to your computer and use it in GitHub Desktop.
Simple Mail client that uses JavaMail for android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Properties; | |
import javax.mail.Authenticator; | |
import javax.mail.Folder; | |
import javax.mail.MessagingException; | |
import javax.mail.Session; | |
import javax.mail.Store; | |
import android.support.annotation.Nullable; | |
import android.support.annotation.WorkerThread; | |
import android.util.Log; | |
public class MailClient extends Authenticator { | |
private static final String TAG = MailClient.class.getSimpleName(); | |
private static final int IMAP_PORT = 993; | |
private static final String IMAP_HOST = "Your mail server"; | |
private final MailUser mMailUser; | |
/** | |
* Creates a Basic mail client to check the user's passed in new messages | |
* | |
* @param MailUser | |
*/ | |
public MailClient(MailUser mailUser) { | |
this.mMailUser = mailUser; | |
} | |
/** | |
* Connects to the user inbox.<BR/> | |
* <b>Should be called on a worker thread as it involves networks calls.</b> | |
* | |
* @return store the users virtual mail box | |
*/ | |
@WorkerThread | |
@Nullable | |
public Store connectInbox() { | |
try { | |
Properties props = getIMAPProperties(); | |
Session session = Session.getInstance(props, this); | |
Store store = session.getStore("imaps"); | |
store.connect(IMAP_HOST, IMAP_PORT, mTwinMailUser.getEmailAddress(), mMailUser.getEmailPassword()); | |
return store; | |
} catch (MessagingException e) { | |
Log.e(TAG, e.getMessage(), e); | |
} | |
return null; | |
} | |
/** | |
* Gets the users messages filtered on unread ones | |
* | |
* @param store | |
* @return the number of unread messages | |
* @throws MessagingException | |
*/ | |
public int getUnreadMessageCount(Store store) throws MessagingException { | |
if (store == null) { | |
return 0; | |
} | |
Folder inbox = store.getFolder("Inbox"); | |
return inbox.getUnreadMessageCount(); | |
} | |
private Properties getIMAPProperties() { | |
Properties props = new Properties(); | |
props.put("mail.imap.host", IMAP_HOST); | |
if (BuildConfig.DEBUG) { | |
props.put("mail.debug", "true"); | |
} | |
props.put("mail.imap.auth", "true"); | |
props.put("mail.imap.starttls.enable", "true"); | |
props.put("mail.imap.port", IMAP_PORT); | |
props.put("mail.imap.socketFactory.port", IMAP_PORT); | |
props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); | |
props.put("mail.imap.socketFactory.fallback", "false"); | |
return props; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment