diff --git a/GmailQuickStart/.gitignore b/GmailQuickStart/.gitignore
new file mode 100644
index 0000000..c6cbe56
--- /dev/null
+++ b/GmailQuickStart/.gitignore
@@ -0,0 +1,8 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+.DS_Store
+/build
+/captures
diff --git a/GmailQuickStart/.idea/.name b/GmailQuickStart/.idea/.name
new file mode 100644
index 0000000..c42fde8
--- /dev/null
+++ b/GmailQuickStart/.idea/.name
@@ -0,0 +1 @@
+GmailQuickStart
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/compiler.xml b/GmailQuickStart/.idea/compiler.xml
new file mode 100644
index 0000000..96cc43e
--- /dev/null
+++ b/GmailQuickStart/.idea/compiler.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/copyright/profiles_settings.xml b/GmailQuickStart/.idea/copyright/profiles_settings.xml
new file mode 100644
index 0000000..e7bedf3
--- /dev/null
+++ b/GmailQuickStart/.idea/copyright/profiles_settings.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/gradle.xml b/GmailQuickStart/.idea/gradle.xml
new file mode 100644
index 0000000..8d2df47
--- /dev/null
+++ b/GmailQuickStart/.idea/gradle.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/misc.xml b/GmailQuickStart/.idea/misc.xml
new file mode 100644
index 0000000..7158618
--- /dev/null
+++ b/GmailQuickStart/.idea/misc.xml
@@ -0,0 +1,62 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 1.8
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/modules.xml b/GmailQuickStart/.idea/modules.xml
new file mode 100644
index 0000000..2d2eb1d
--- /dev/null
+++ b/GmailQuickStart/.idea/modules.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/runConfigurations.xml b/GmailQuickStart/.idea/runConfigurations.xml
new file mode 100644
index 0000000..7f68460
--- /dev/null
+++ b/GmailQuickStart/.idea/runConfigurations.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/.idea/vcs.xml b/GmailQuickStart/.idea/vcs.xml
new file mode 100644
index 0000000..6564d52
--- /dev/null
+++ b/GmailQuickStart/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/Libs/activation.jar b/GmailQuickStart/Libs/activation.jar
new file mode 100644
index 0000000..614a03c
Binary files /dev/null and b/GmailQuickStart/Libs/activation.jar differ
diff --git a/GmailQuickStart/Libs/additionnal.jar b/GmailQuickStart/Libs/additionnal.jar
new file mode 100644
index 0000000..aeb9611
Binary files /dev/null and b/GmailQuickStart/Libs/additionnal.jar differ
diff --git a/GmailQuickStart/Libs/mail.jar b/GmailQuickStart/Libs/mail.jar
new file mode 100644
index 0000000..ea594fd
Binary files /dev/null and b/GmailQuickStart/Libs/mail.jar differ
diff --git a/GmailQuickStart/app/.gitignore b/GmailQuickStart/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/GmailQuickStart/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/GmailQuickStart/app/build.gradle b/GmailQuickStart/app/build.gradle
new file mode 100644
index 0000000..1308efa
--- /dev/null
+++ b/GmailQuickStart/app/build.gradle
@@ -0,0 +1,50 @@
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 23
+ buildToolsVersion "23.0.2"
+
+ defaultConfig {
+ applicationId "com.example.gmailquickstart"
+ minSdkVersion 16
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ packagingOptions {
+
+ exclude 'META-INF/LICENSE.txt'
+ exclude 'META-INF/NOTICE.txt'
+
+ }
+}
+
+dependencies {
+ compile fileTree(include: ['*.jar'], dir: 'libs')
+ testCompile 'junit:junit:4.12'
+ compile('com.google.api-client:google-api-client-android:1.20.0') {
+ exclude group: 'org.apache.httpcomponents'
+ }
+ compile('com.google.apis:google-api-services-gmail:v1-rev29-1.20.0') {
+ exclude group: 'org.apache.httpcomponents'
+ }
+ compile 'com.android.support:appcompat-v7:23.2.0'
+ compile 'com.google.android.gms:play-services-identity:7.8.0'
+ // compile 'javax.mail:javax.mail-api:1.5.5'
+ compile 'com.android.support:support-v4:23.2.0'
+ compile 'com.android.support:recyclerview-v7:23.2.0'
+ compile 'com.android.support:design:23.2.0'
+ // compile files ('Libs/activation.jar')
+ // compile files ('Libs/additional.jar')
+ // compile files ('Libs/mail.jar')
+ //compile 'com.sun.mail:javax.mail:1.5.5'
+ compile files('/Users/nat/Networking-in-Android/emailApp/GmailQuickStart/Libs/activation.jar')
+ compile files('/Users/nat/Networking-in-Android/emailApp/GmailQuickStart/Libs/additionnal.jar')
+ compile files('/Users/nat/Networking-in-Android/emailApp/GmailQuickStart/Libs/mail.jar')
+}
diff --git a/GmailQuickStart/app/proguard-rules.pro b/GmailQuickStart/app/proguard-rules.pro
new file mode 100644
index 0000000..e6398d3
--- /dev/null
+++ b/GmailQuickStart/app/proguard-rules.pro
@@ -0,0 +1,17 @@
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in /Users/nat/Library/Android/sdk/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the proguardFiles
+# directive in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
diff --git a/GmailQuickStart/app/src/androidTest/java/com/example/gmailquickstart/ApplicationTest.java b/GmailQuickStart/app/src/androidTest/java/com/example/gmailquickstart/ApplicationTest.java
new file mode 100644
index 0000000..796e71b
--- /dev/null
+++ b/GmailQuickStart/app/src/androidTest/java/com/example/gmailquickstart/ApplicationTest.java
@@ -0,0 +1,13 @@
+package com.example.gmailquickstart;
+
+import android.app.Application;
+import android.test.ApplicationTestCase;
+
+/**
+ * Testing Fundamentals
+ */
+public class ApplicationTest extends ApplicationTestCase {
+ public ApplicationTest() {
+ super(Application.class);
+ }
+}
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/AndroidManifest.xml b/GmailQuickStart/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..5d18709
--- /dev/null
+++ b/GmailQuickStart/app/src/main/AndroidManifest.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/ComposeActivity.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/ComposeActivity.java
new file mode 100644
index 0000000..0060276
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/ComposeActivity.java
@@ -0,0 +1,124 @@
+package com.example.gmailquickstart;
+
+import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+
+import com.example.gmailquickstart.emailStuff.EMailManager;
+import com.example.gmailquickstart.emailStuff.Email;
+import com.example.gmailquickstart.emailStuff.SendEmailThread;
+
+import java.util.ArrayList;
+
+public class ComposeActivity extends AppCompatActivity {
+
+ boolean mIsDraftOriginally=false;
+ String mUser="";
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_compose);
+
+ String theID = getIntent().getStringExtra("DRAFT");
+ if(theID!=null){
+ //this is a draft
+ mIsDraftOriginally=true;
+ //set the stuff up from the draft
+ EMailManager emailManager = EMailManager.getInstance();
+ Email mail =emailManager.getEmailByID(theID);
+ EditText toEditText = (EditText)findViewById(R.id.to_edit_text);
+ ArrayListrecipients = mail.getToData();
+ String recipientsField="";
+ int total = recipients.size();
+ for(int i=0;i()));
+ }
+
+ //OVERIDDEN METHODS BELOW
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ MenuInflater inflater = getMenuInflater();
+ inflater.inflate(R.menu.options_menu, menu);
+
+ // Associate searchable configuration with the SearchView
+ SearchManager searchManager =
+ (SearchManager) getSystemService(Context.SEARCH_SERVICE);
+ SearchView searchView =
+ (SearchView) menu.findItem(R.id.search).getActionView();
+ searchView.setSearchableInfo(
+ searchManager.getSearchableInfo(getComponentName()));
+
+ return true;
+ }
+
+ /**
+ * Called whenever this activity is pushed to the foreground, such as after
+ * a call to onCreate().
+ */
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Log.d("EmailListActivity","onResume about to see if I should refresh");
+ if (isGooglePlayServicesAvailable()) {
+ if(EmailListActivity.this.isRequestedViaSearch==false) {
+ Log.d("EmailListActivity","onResume about to see if I should refresh--ABOUT CO CALL REFERSH RESULTS");
+ refreshResults();
+ }else{
+ Log.d("EmailListActivity","onResume about to see if I should refresh --setting search variable to false");
+ EmailListActivity.this.isRequestedViaSearch=false;
+ }
+ } else {
+ Toast.makeText(EmailListActivity.this,"Google Play Services required: after installing, close and relaunch this app.",Toast.LENGTH_LONG).show();
+ }
+ }
+ /**
+ * Called when an activity launched here (specifically, AccountPicker
+ * and authorization) exits, giving you the requestCode you started it with,
+ * the resultCode it returned, and any additional data from it.
+ * @param requestCode code indicating which activity result is incoming.
+ * @param resultCode code indicating the result of the incoming
+ * activity result.
+ * @param data Intent (containing result data) returned by incoming
+ * activity result.
+ */
+ @Override
+ protected void onActivityResult(
+ int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ switch(requestCode) {
+ case COMPOSE_EMAIL:
+ if(resultCode==RESULT_OK & data!=null){
+ boolean result = data.getBooleanExtra("RESULT_OF_COMPOSE",false);
+ if(result==false){
+ Toast.makeText(EmailListActivity.this,"Message could not be sent or saved as a draft successfully",Toast.LENGTH_LONG).show();
+ }
+ }
+ break;
+ case REQUEST_GOOGLE_PLAY_SERVICES:
+ if (resultCode != RESULT_OK) {
+ isGooglePlayServicesAvailable();
+ }
+ break;
+ case REQUEST_ACCOUNT_PICKER:
+ Log.d("MainActivity", "Inside request account picker");
+ if (resultCode == RESULT_OK && data != null &&
+ data.getExtras() != null) {
+ String accountName =
+ data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
+ if (accountName != null) {
+ Log.d("MainActivity","Inside request account picker with "+accountName);
+ mCredential.setSelectedAccountName(accountName);
+ SharedPreferences settings =
+ getPreferences(Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = settings.edit();
+ editor.putString(PREF_ACCOUNT_NAME, accountName);
+ editor.apply();
+ }
+ } else if (resultCode == RESULT_CANCELED) {
+ mOutputText.setText("Account unspecified.");
+ }
+ break;
+ case REQUEST_AUTHORIZATION:
+ if (resultCode != RESULT_OK) {
+ chooseAccount();
+ }
+ break;
+ }
+
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ @Override
+ protected void onNewIntent(Intent intent) {
+ handleIntent(intent);
+ }
+
+ private void handleIntent(Intent intent) {
+
+ if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
+ this.searchString = intent.getStringExtra(SearchManager.QUERY);
+ this.isRequestedViaSearch=true;
+ if(isDisplayingDraft){
+ EMailManager.getInstance().clearEmails();
+ new MakeRequestTask(mCredential).execute("DRAFT");
+ }else{
+ EMailManager.getInstance().clearEmails();
+ new MakeRequestTask(mCredential).execute("INBOX","CATEGORY_PERSONAL");
+ }
+ }
+ }
+ //methods from Google API example
+ /**
+ * Attempt to get a set of data from the Gmail API to display. If the
+ * email address isn't known yet, then call chooseAccount() method so the
+ * user can pick an account.
+ */
+ private void refreshResults() {
+ if (mCredential.getSelectedAccountName() == null) {
+ chooseAccount();
+ } else {
+ if (isDeviceOnline()) {
+ EMailManager emailManager = EMailManager.getInstance();
+ if(emailManager.isTimeToUpdate()) {
+ Log.d("EmailListActivity","About time to call UPDATE");
+ new MakeRequestTask(mCredential).execute();
+ }else{
+ Log.d("EmailListActivity","TO SOON TO UPDATE");
+ }
+ } else {
+ Toast.makeText(EmailListActivity.this,"no network connection avail",Toast.LENGTH_LONG).show();
+ //mOutputText.setText("No network connection available.");
+ }
+ }
+ }
+
+ /**
+ * Starts an activity in Google Play Services so the user can pick an
+ * account.
+ */
+ private void chooseAccount() {
+ startActivityForResult(
+ mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
+ }
+
+ /**
+ * Checks whether the device currently has a network connection.
+ * @return true if the device has a network connection, false otherwise.
+ */
+ private boolean isDeviceOnline() {
+ ConnectivityManager connMgr =
+ (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
+ return (networkInfo != null && networkInfo.isConnected());
+ }
+
+ /**
+ * Check that Google Play services APK is installed and up to date. Will
+ * launch an error dialog for the user to update Google Play Services if
+ * possible.
+ * @return true if Google Play Services is available and up to
+ * date on this device; false otherwise.
+ */
+ private boolean isGooglePlayServicesAvailable() {
+ final int connectionStatusCode =
+ GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
+ if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
+ showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
+ return false;
+ } else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Display an error dialog showing that Google Play Services is missing
+ * or out of date.
+ * @param connectionStatusCode code describing the presence (or lack of)
+ * Google Play Services on this device.
+ */
+ void showGooglePlayServicesAvailabilityErrorDialog(
+ final int connectionStatusCode) {
+ Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
+ connectionStatusCode,
+ EmailListActivity.this,
+ REQUEST_GOOGLE_PLAY_SERVICES);
+ dialog.show();
+ }
+
+ //method to send mail
+
+ ///INNER CLASSES BELOW
+ public class SimpleItemRecyclerViewAdapter
+ extends RecyclerView.Adapter {
+
+ private final List mValues;
+
+ public SimpleItemRecyclerViewAdapter(List items) {
+ mValues = items;
+ }
+
+ public void changeUnderlyingValues(ArrayList listEmails){
+ mValues.clear();
+ for(Email email:listEmails) {
+ mValues.add(email);
+ }
+
+ }
+ @Override
+ public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ View view = LayoutInflater.from(parent.getContext())
+ .inflate(R.layout.email_list_content, parent, false);
+ return new ViewHolder(view);
+ }
+
+ @Override
+ public void onBindViewHolder(final ViewHolder holder, int position) {
+ holder.mItem = mValues.get(position);
+ holder.mSubjectView.setText(mValues.get(position).getSubject());
+ holder.mContentView.setText(mValues.get(position).getSnippet());
+
+ holder.mView.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Log.d("EmailListActivity","inside onclick listener");
+ if (mTwoPane) {
+ if(holder.mItem.isDraft()){
+ Context context = v.getContext();
+ Intent intent = new Intent(context, ComposeActivity.class);
+ intent.putExtra("DRAFT", holder.mItem.getTheID());
+
+ context.startActivity(intent);
+ }else {
+ Log.d("EmailListActivity", "about to do detail activity fragment with id of " + holder.mItem.getTheID());
+ Bundle arguments = new Bundle();
+ arguments.putString(emailDetailFragment.ARG_ITEM_ID, holder.mItem.getTheID());
+
+ emailDetailFragment fragment = new emailDetailFragment();
+ fragment.setArguments(arguments);
+ getSupportFragmentManager().beginTransaction()
+ .replace(R.id.email_detail_container, fragment)
+ .commit();
+ }
+ } else {
+
+ if(holder.mItem.isDraft()){
+ Context context = v.getContext();
+ Intent intent = new Intent(context, ComposeActivity.class);
+ intent.putExtra("DRAFT", holder.mItem.getTheID());
+
+ context.startActivity(intent);
+ }else {
+ Context context = v.getContext();
+ Intent intent = new Intent(context, emailDetailActivity.class);
+ intent.putExtra(emailDetailFragment.ARG_ITEM_ID, holder.mItem.getTheID());
+
+ context.startActivity(intent);
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public int getItemCount() {
+ return mValues.size();
+ }
+
+ public class ViewHolder extends RecyclerView.ViewHolder {
+ public final View mView;
+ public final TextView mSubjectView;
+ public final TextView mContentView;
+ public Email mItem;
+
+
+ public ViewHolder(View view) {
+ super(view);
+ mView = view;
+ mSubjectView = (TextView) view.findViewById(R.id.theSubject);
+ mContentView = (TextView) view.findViewById(R.id.content);
+ }
+
+
+
+
+ @Override
+ public String toString() {
+ return super.toString() + " '" + mContentView.getText() + "'";
+ }
+ }
+ }
+
+ //////////////////////////////////////////
+ /**
+ * An asynchronous task that handles the Gmail API call.
+ * Placing the API calls in their own task ensures the UI stays responsive.
+ */
+ private class MakeRequestTask extends AsyncTask {
+ private com.google.api.services.gmail.Gmail mService = null;
+ private Exception mLastError = null;
+
+ public MakeRequestTask(GoogleAccountCredential credential) {
+ HttpTransport transport = AndroidHttp.newCompatibleTransport();
+ JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
+ mService = new com.google.api.services.gmail.Gmail.Builder(
+ transport, jsonFactory, credential)
+ .setApplicationName("Gmail API Android Quickstart")
+ .build();
+ }
+
+ /**
+ * Background task to call Gmail API.
+ * @param params no parameters needed for this task.
+ */
+ @Override
+ protected Void doInBackground(String... params) {
+ try {
+ getDataFromApi(params);
+ } catch (Exception e) {
+ mLastError = e;
+ cancel(true);
+ return null;
+ }
+ return null;
+ }
+
+ /**
+ * Fetch a list of Gmail labels attached to the specified account.
+ * @return List of Strings labels.
+ * @throws IOException
+ */
+ private void getDataFromApi(String[] theSelectedLabels) throws IOException {
+ // Get the labels in the user's account.
+ String user = "me";
+
+
+
+
+ //get message id
+ ArrayList theLabels = new ArrayList<>();
+ if(theSelectedLabels==null ||theSelectedLabels.length==0) {
+ theLabels.add("INBOX");
+ //theLabels.add("CATEGORY_PERSONAL");
+
+ }else{
+ for(int i=0;i headerContainer = (ArrayList) actualMessage.getPayload().getHeaders();
+ String emailSubject=" ";
+ String emailTo="";
+ String emailFrom="";
+ for (MessagePartHeader messagePartHeader : headerContainer) {
+ if (messagePartHeader.getName().equals("Subject")) {
+ emailSubject = messagePartHeader.getValue();
+ Log.d("emailListActivity", "subject " + emailSubject);
+ }else if(messagePartHeader.getName().equals("To")){
+ emailTo=messagePartHeader.getValue();
+ }else if(messagePartHeader.getName().equals("From")){
+ emailFrom=messagePartHeader.getValue();
+
+ }
+ }
+ ArrayList messageParts= (ArrayList)actualMessage.getPayload().getParts();
+ Log.d("EmailListActivity","About to loop through messageParts of message "+message.getId());
+
+ String htmlData="";
+ String plainData="";
+ if(messageParts!=null) {
+ for (MessagePart m : messageParts) {
+ if (m.getMimeType().contains("multipart")) {
+ Log.d("EmailListActivity", "This message contains multipart");
+ ArrayList parts = (ArrayList) m.getParts();
+ Log.d("EmailListActivity", "size is " + parts.size());
+ for (MessagePart p : parts) {
+ Log.d("EmailListActivity", "Looping through message parts " + p.getMimeType());
+ if (p.getMimeType().contains("html")) {
+ Log.d("EmailListActivity", "attempting to access html data");
+ htmlData = new String(Base64.decodeBase64(p.getBody().getData()));
+ Log.d("EmailListActivity", "attempting to access html data " + htmlData);
+ } else if (p.getMimeType().contains("plain")) {
+ Log.d("EmailListActivity", "attempting to access plain data");
+ plainData = new String(Base64.decodeBase64(p.getBody().getData()));
+ Log.d("EmailListActivity", "attempting to access plain data " + plainData);
+ }
+ }
+
+ }
+
+
+ }
+ }else{
+
+ plainData = new String(Base64.decodeBase64(actualMessage.getPayload().getBody().getData()));
+ }
+
+
+
+ Email newEmail = new Email();
+ newEmail.setSnippet(actualMessage.getSnippet());
+ newEmail.setTheID(actualMessage.getId());
+ newEmail.setSubject(emailSubject);
+ Log.d("EmailListActivity","htmlData:"+htmlData);
+ Log.d("EmailListActivity","plainData "+plainData);
+ if(htmlData.equals("")){
+ Log.d("EmailListActivity","using plain text");
+ newEmail.setBodyData(plainData);
+ newEmail.setType("text");
+ }else {
+ Log.d("EmailListActivity","using html text");
+ newEmail.setBodyData(htmlData);
+ newEmail.setType("html");
+ }
+ if(theSelectedLabels!=null&&theSelectedLabels.length>0&&theSelectedLabels[0].equals("DRAFT")){
+ newEmail.setIsDraft(true);
+ }
+ newEmail.addTo(emailTo);
+ newEmail.setFromData(emailFrom);
+ emailManager.addEmail(newEmail);
+
+ Log.d("MainActivity", "Subject: " + emailSubject+" id "+actualMessage.getId());
+ //Log.d("MainActivity", "Message snippet: " + actualMessage.getSnippet());
+
+ }
+ emailManager.endUpdate();
+
+
+
+ }
+
+
+
+ @Override
+ protected void onPreExecute() {
+ //mOutputText.setText("");
+ mProgress.show();
+ }
+
+ @Override
+ protected void onPostExecute(Void aVoid ) {
+ mProgress.hide();
+ EMailManager eMailManager = EMailManager.getInstance();
+ eMailManager.printAllToLog();
+
+ RecyclerView recyclerView = (RecyclerView)EmailListActivity.this.findViewById(R.id.email_list);
+ SimpleItemRecyclerViewAdapter theAdapter= (SimpleItemRecyclerViewAdapter) recyclerView.getAdapter();
+ theAdapter.changeUnderlyingValues(eMailManager.getAllEmails());
+ theAdapter.notifyDataSetChanged();
+
+ }
+
+
+
+ @Override
+ protected void onCancelled() {
+ mProgress.hide();
+ if (mLastError != null) {
+ if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
+ showGooglePlayServicesAvailabilityErrorDialog(
+ ((GooglePlayServicesAvailabilityIOException) mLastError)
+ .getConnectionStatusCode());
+ } else if (mLastError instanceof UserRecoverableAuthIOException) {
+ startActivityForResult(
+ ((UserRecoverableAuthIOException) mLastError).getIntent(),
+ MainActivity.REQUEST_AUTHORIZATION);
+ } else {
+ //mOutputText.setText("The following error occurred:\n"
+ // + mLastError.getMessage());
+ }
+ } else {
+ //mOutputText.setText("Request cancelled.");
+ }
+ }
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/MainActivity.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/MainActivity.java
new file mode 100644
index 0000000..3caee9d
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/MainActivity.java
@@ -0,0 +1,438 @@
+package com.example.gmailquickstart;
+
+import android.accounts.AccountManager;
+import android.app.Activity;
+import android.app.Dialog;
+import android.app.ProgressDialog;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.text.TextUtils;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.GooglePlayServicesUtil;
+import com.google.api.client.extensions.android.http.AndroidHttp;
+import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
+import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
+import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
+import com.google.api.client.http.HttpTransport;
+import com.google.api.client.json.JsonFactory;
+import com.google.api.client.json.jackson2.JacksonFactory;
+import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
+import com.google.api.client.util.ExponentialBackOff;
+import com.google.api.services.gmail.Gmail;
+import com.google.api.services.gmail.GmailScopes;
+import com.google.api.services.gmail.model.Label;
+import com.google.api.services.gmail.model.ListLabelsResponse;
+import com.google.api.services.gmail.model.Message;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+
+public class MainActivity extends Activity {
+ GoogleAccountCredential mCredential;
+ private TextView mOutputText;
+ ProgressDialog mProgress;
+
+ static final int REQUEST_ACCOUNT_PICKER = 1000;
+ static final int REQUEST_AUTHORIZATION = 1001;
+ static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
+ private static final String PREF_ACCOUNT_NAME = "nat2014111@gmail.com";//"accountName";
+ private static final String[] SCOPES = { GmailScopes.GMAIL_LABELS,GmailScopes.GMAIL_READONLY,GmailScopes.GMAIL_COMPOSE };
+
+ /**
+ * Create the main activity.
+ * @param savedInstanceState previously saved instance data.
+ */
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ LinearLayout activityLayout = new LinearLayout(this);
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.MATCH_PARENT);
+ activityLayout.setLayoutParams(lp);
+ activityLayout.setOrientation(LinearLayout.VERTICAL);
+ activityLayout.setPadding(16, 16, 16, 16);
+
+ ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT);
+
+ mOutputText = new TextView(this);
+ mOutputText.setLayoutParams(tlp);
+ mOutputText.setPadding(16, 16, 16, 16);
+ mOutputText.setVerticalScrollBarEnabled(true);
+ mOutputText.setMovementMethod(new ScrollingMovementMethod());
+ activityLayout.addView(mOutputText);
+
+ Button showEmailButton = new Button(this);
+ activityLayout.addView(showEmailButton);
+
+
+ mProgress = new ProgressDialog(this);
+ mProgress.setMessage("Calling Gmail API ...");
+
+ setContentView(activityLayout);
+
+ // Initialize credentials and service object.
+ SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
+ mCredential = GoogleAccountCredential.usingOAuth2(
+ getApplicationContext(), Arrays.asList(SCOPES))
+ .setBackOff(new ExponentialBackOff())
+ .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
+ }
+
+
+ /**
+ * Called whenever this activity is pushed to the foreground, such as after
+ * a call to onCreate().
+ */
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (isGooglePlayServicesAvailable()) {
+ refreshResults();
+ } else {
+ mOutputText.setText("Google Play Services required: " +
+ "after installing, close and relaunch this app.");
+ }
+ }
+
+ /**
+ * Called when an activity launched here (specifically, AccountPicker
+ * and authorization) exits, giving you the requestCode you started it with,
+ * the resultCode it returned, and any additional data from it.
+ * @param requestCode code indicating which activity result is incoming.
+ * @param resultCode code indicating the result of the incoming
+ * activity result.
+ * @param data Intent (containing result data) returned by incoming
+ * activity result.
+ */
+ @Override
+ protected void onActivityResult(
+ int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ switch(requestCode) {
+ case REQUEST_GOOGLE_PLAY_SERVICES:
+ if (resultCode != RESULT_OK) {
+ isGooglePlayServicesAvailable();
+ }
+ break;
+ case REQUEST_ACCOUNT_PICKER:
+ Log.d("MainActivity","Inside request account picker");
+ if (resultCode == RESULT_OK && data != null &&
+ data.getExtras() != null) {
+ String accountName =
+ data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
+ if (accountName != null) {
+ Log.d("MainActivity","Inside request account picker with "+accountName);
+ mCredential.setSelectedAccountName(accountName);
+ SharedPreferences settings =
+ getPreferences(Context.MODE_PRIVATE);
+ SharedPreferences.Editor editor = settings.edit();
+ editor.putString(PREF_ACCOUNT_NAME, accountName);
+ editor.apply();
+ }
+ } else if (resultCode == RESULT_CANCELED) {
+ //mOutputText.setText("Account unspecified.");
+ }
+ break;
+ case REQUEST_AUTHORIZATION:
+ if (resultCode != RESULT_OK) {
+ chooseAccount();
+ }
+ break;
+ }
+
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ /**
+ * Attempt to get a set of data from the Gmail API to display. If the
+ * email address isn't known yet, then call chooseAccount() method so the
+ * user can pick an account.
+ */
+ private void refreshResults() {
+ if (mCredential.getSelectedAccountName() == null) {
+ chooseAccount();
+ } else {
+ if (isDeviceOnline()) {
+ new MakeRequestTask(mCredential).execute();
+ } else {
+ Toast.makeText(MainActivity.this,"no network connection avail",Toast.LENGTH_LONG).show();
+ mOutputText.setText("No network connection available.");
+ }
+ }
+ }
+
+ /**
+ * Starts an activity in Google Play Services so the user can pick an
+ * account.
+ */
+ private void chooseAccount() {
+ startActivityForResult(
+ mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
+ }
+
+ /**
+ * Checks whether the device currently has a network connection.
+ * @return true if the device has a network connection, false otherwise.
+ */
+ private boolean isDeviceOnline() {
+ ConnectivityManager connMgr =
+ (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
+ return (networkInfo != null && networkInfo.isConnected());
+ }
+
+ /**
+ * Check that Google Play services APK is installed and up to date. Will
+ * launch an error dialog for the user to update Google Play Services if
+ * possible.
+ * @return true if Google Play Services is available and up to
+ * date on this device; false otherwise.
+ */
+ private boolean isGooglePlayServicesAvailable() {
+ final int connectionStatusCode =
+ GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
+ if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
+ showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
+ return false;
+ } else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Display an error dialog showing that Google Play Services is missing
+ * or out of date.
+ * @param connectionStatusCode code describing the presence (or lack of)
+ * Google Play Services on this device.
+ */
+ void showGooglePlayServicesAvailabilityErrorDialog(
+ final int connectionStatusCode) {
+ Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
+ connectionStatusCode,
+ MainActivity.this,
+ REQUEST_GOOGLE_PLAY_SERVICES);
+ dialog.show();
+ }
+
+
+
+
+
+ public static boolean sendMail(Gmail service, String from, List to, String title, String body) {
+ if (service == null) {
+ return false;
+ }
+ Message message = new Message();
+
+ StringBuilder builder = new StringBuilder();
+ builder.append("From: ");
+ builder.append(from);
+ builder.append("\nTo: ");
+ if (to != null) {
+ int toSize = to.size();
+ for (int i = 0; i < toSize; i++) {
+ String tmp = to.get(i).replace(",", "");
+ builder.append(tmp);
+ if (i < toSize - 1) {
+ builder.append(", ");
+ }
+ }
+ }
+ builder.append("\nDate: ");
+ SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
+ String date = sdf.format(new Date());
+ builder.append(date);
+ builder.append("\nMIME-Version: 1.0\nSubject: =?ISO-2022-JP?B?");
+ if (title != null) {
+ try {
+ builder.append(Base64.encodeBase64URLSafeString(title.getBytes("ISO-2022-JP")));
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ }
+ builder.append("?=");
+ builder.append("\nContent-Type: text/plain; charset=ISO-2022-JP;");
+ builder.append("\nContent-Transfer-Encoding: 7bit");
+ builder.append("\n\n");
+ builder.append(body);
+
+ String encodedEmail = Base64.encodeBase64URLSafeString(builder.toString().getBytes());
+
+ message.setRaw(encodedEmail);
+
+ boolean result = false;
+
+ try {
+ message = service.users().messages().send("me", message).execute();
+ result = true;
+ } catch (UserRecoverableAuthIOException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return result;
+ }
+ /**
+ * An asynchronous task that handles the Gmail API call.
+ * Placing the API calls in their own task ensures the UI stays responsive.
+ */
+ private class MakeRequestTask extends AsyncTask> {
+ private com.google.api.services.gmail.Gmail mService = null;
+ private Exception mLastError = null;
+
+ public MakeRequestTask(GoogleAccountCredential credential) {
+ HttpTransport transport = AndroidHttp.newCompatibleTransport();
+
+
+
+
+ JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
+ mService = new com.google.api.services.gmail.Gmail.Builder(
+ transport, jsonFactory, credential)
+ .setApplicationName("Gmail API Android Quickstart")
+ .build();
+
+
+
+ }
+
+ /**
+ * Background task to call Gmail API.
+ * @param params no parameters needed for this task.
+ */
+ @Override
+ protected List doInBackground(Void... params) {
+ try {
+ return getDataFromApi();
+ } catch (Exception e) {
+ mLastError = e;
+ cancel(true);
+ return null;
+ }
+ }
+
+ /**
+ * Fetch a list of Gmail labels attached to the specified account.
+ * @return List of Strings labels.
+ * @throws IOException
+ */
+ private List getDataFromApi() throws IOException {
+ // Get the labels in the user's account.
+ String user = "me";
+ List labels = new ArrayList();
+
+ //labels
+ ListLabelsResponse listResponse = mService.users().labels().list(user).execute();
+ for (Label label : listResponse.getLabels()) {
+ labels.add(label.getName());
+ }
+
+ //get message id
+ /*ListMessagesResponse response = mService.users().messages().list(user).setQ("google").execute();
+ for (Message message : response.getMessages()) {
+ //labels.add(message.getId());
+ Message actualMessage = mService.users().messages().get(user, message.getId()).execute();
+
+ Log.d("MainActivity","Message snippet: " + actualMessage.getSnippet());
+ }*/
+ /*List messages = new ArrayList();
+ while (response.getMessages() != null) {
+ messages.addAll(response.getMessages());
+ if (response.getNextPageToken() != null) {
+ String pageToken = response.getNextPageToken();
+ response = mService.users().messages().list(user).setQ("google")
+ .setPageToken(pageToken).execute();
+ } else {
+ break;
+ }
+ }
+
+ for (Message message : messages) {
+ Log.d("MainActivity",message.toPrettyString());
+ }*/
+
+ //send email
+ /* try {
+ MimeMessage email = createEmail("natpanchee@yahoo.com", user, "THIS IS FROM THE APP", "THIS IS A MESSAGE FROM THE APP");
+ Message message = createMessageWithEmail(email);
+ message = mService.users().messages().send(user, message).execute();
+
+ System.out.println("Message id: " + message.getId());
+ System.out.println(message.toPrettyString());
+ }catch(MessagingException me){
+ me.printStackTrace();
+ Toast.makeText(MainActivity.this,"There was an error sending your message",Toast.LENGTH_SHORT).show();
+ }*/
+ //Gmail service, String from, List to, String title, String body
+ ArrayListtoPerson = new ArrayList<>();
+ toPerson.add("natpanchee@Yahoo.com");
+ sendMail(mService, "nat2014111@gmail.com", toPerson, "TEST", "This is the body of the email");
+ return labels;
+ }
+
+
+
+ @Override
+ protected void onPreExecute() {
+ mOutputText.setText("");
+ mProgress.show();
+ }
+
+ @Override
+ protected void onPostExecute(List output) {
+ mProgress.hide();
+ if (output == null || output.size() == 0) {
+ mOutputText.setText("No results returned.");
+ } else {
+ output.add(0, "Data retrieved using the Gmail API:");
+ mOutputText.setText(TextUtils.join("\n", output));
+ }
+ }
+
+ @Override
+ protected void onCancelled() {
+ mProgress.hide();
+ if (mLastError != null) {
+ if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
+ showGooglePlayServicesAvailabilityErrorDialog(
+ ((GooglePlayServicesAvailabilityIOException) mLastError)
+ .getConnectionStatusCode());
+ } else if (mLastError instanceof UserRecoverableAuthIOException) {
+ startActivityForResult(
+ ((UserRecoverableAuthIOException) mLastError).getIntent(),
+ MainActivity.REQUEST_AUTHORIZATION);
+ } else {
+ mOutputText.setText("The following error occurred:\n"
+ + mLastError.getMessage());
+ }
+ } else {
+ mOutputText.setText("Request cancelled.");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/dummy/DummyContent.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/dummy/DummyContent.java
new file mode 100644
index 0000000..e9e8e11
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/dummy/DummyContent.java
@@ -0,0 +1,72 @@
+package com.example.gmailquickstart.dummy;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Helper class for providing sample content for user interfaces created by
+ * Android template wizards.
+ *
+ * TODO: Replace all uses of this class before publishing your app.
+ */
+public class DummyContent {
+
+ /**
+ * An array of sample (dummy) items.
+ */
+ public static final List ITEMS = new ArrayList();
+
+ /**
+ * A map of sample (dummy) items, by ID.
+ */
+ public static final Map ITEM_MAP = new HashMap();
+
+ private static final int COUNT = 25;
+
+ static {
+ // Add some sample items.
+ for (int i = 1; i <= COUNT; i++) {
+ addItem(createDummyItem(i));
+ }
+ }
+
+ private static void addItem(DummyItem item) {
+ ITEMS.add(item);
+ ITEM_MAP.put(item.id, item);
+ }
+
+ private static DummyItem createDummyItem(int position) {
+ return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
+ }
+
+ private static String makeDetails(int position) {
+ StringBuilder builder = new StringBuilder();
+ builder.append("Details about Item: ").append(position);
+ for (int i = 0; i < position; i++) {
+ builder.append("\nMore details information here.");
+ }
+ return builder.toString();
+ }
+
+ /**
+ * A dummy item representing a piece of content.
+ */
+ public static class DummyItem {
+ public final String id;
+ public final String content;
+ public final String details;
+
+ public DummyItem(String id, String content, String details) {
+ this.id = id;
+ this.content = content;
+ this.details = details;
+ }
+
+ @Override
+ public String toString() {
+ return content;
+ }
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailActivity.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailActivity.java
new file mode 100644
index 0000000..dfbe93e
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailActivity.java
@@ -0,0 +1,83 @@
+package com.example.gmailquickstart;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.design.widget.FloatingActionButton;
+import android.support.design.widget.Snackbar;
+import android.support.v7.app.ActionBar;
+import android.support.v7.app.AppCompatActivity;
+import android.support.v7.widget.Toolbar;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.Button;
+
+/**
+ * An activity representing a single email detail screen. This
+ * activity is only used narrow width devices. On tablet-size devices,
+ * item details are presented side-by-side with a list of items
+ * in a {@link EmailListActivity}.
+ */
+public class emailDetailActivity extends AppCompatActivity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_email_detail);
+ Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
+ setSupportActionBar(toolbar);
+
+ FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
+ fab.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG)
+ .setAction("Action", null).show();
+ }
+ });
+
+ // Show the Up button in the action bar.
+ ActionBar actionBar = getSupportActionBar();
+ if (actionBar != null) {
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ }
+
+
+ // savedInstanceState is non-null when there is fragment state
+ // saved from previous configurations of this activity
+ // (e.g. when rotating the screen from portrait to landscape).
+ // In this case, the fragment will automatically be re-added
+ // to its container so we don't need to manually add it.
+ // For more information, see the Fragments API guide at:
+ //
+ // http://developer.android.com/guide/components/fragments.html
+ //
+ if (savedInstanceState == null) {
+ // Create the detail fragment and add it to the activity
+ // using a fragment transaction.
+ Bundle arguments = new Bundle();
+ arguments.putString(emailDetailFragment.ARG_ITEM_ID,
+ getIntent().getStringExtra(emailDetailFragment.ARG_ITEM_ID));
+ emailDetailFragment fragment = new emailDetailFragment();
+ fragment.setArguments(arguments);
+ getSupportFragmentManager().beginTransaction()
+ .add(R.id.email_detail_container, fragment)
+ .commit();
+ }
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ int id = item.getItemId();
+ if (id == android.R.id.home) {
+ // This ID represents the Home or Up button. In the case of this
+ // activity, the Up button is shown. For
+ // more details, see the Navigation pattern on Android Design:
+ //
+ // http://developer.android.com/design/patterns/navigation.html#up-vs-back
+ //
+ navigateUpTo(new Intent(this, EmailListActivity.class));
+ return true;
+ }
+ return super.onOptionsItemSelected(item);
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailFragment.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailFragment.java
new file mode 100644
index 0000000..02f9ee6
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailFragment.java
@@ -0,0 +1,134 @@
+package com.example.gmailquickstart;
+
+import android.content.Intent;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.WebView;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.example.gmailquickstart.emailStuff.EMailManager;
+import com.example.gmailquickstart.emailStuff.Email;
+
+/**
+ * A fragment representing a single email detail screen.
+ * This fragment is either contained in a {@link EmailListActivity}
+ * in two-pane mode (on tablets) or a {@link emailDetailActivity}
+ * on handsets.
+ */
+public class emailDetailFragment extends Fragment {
+ /**
+ * The fragment argument representing the item ID that this fragment
+ * represents.
+ */
+ public static final String ARG_ITEM_ID = "item_id";
+
+ /**
+ * The dummy content this fragment is presenting.
+ */
+ private Email mEmail;
+
+ /**
+ * Mandatory empty constructor for the fragment manager to instantiate the
+ * fragment (e.g. upon screen orientation changes).
+ */
+ public emailDetailFragment() {
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ if (getArguments().containsKey(ARG_ITEM_ID)) {
+ // Load the dummy content specified by the fragment
+ // arguments. In a real-world scenario, use a Loader
+ // to load content from a content provider.
+ Log.d("emailFragment","INside onCreate of detail Fragment");
+ String theID = getArguments().getString(ARG_ITEM_ID);
+ Log.d("emailFragment","Inside with theID of "+theID);
+ // mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
+
+ EMailManager eMailManager = EMailManager.getInstance();
+ eMailManager.printAllToLog();
+ mEmail= eMailManager.getEmailByID(theID);
+ Log.d("emailDetailFragment",theID);
+ if(mEmail==null){
+ Log.d("emailDetailFragment","email is null");
+ }else{
+ Log.d("emailDetailFragment","email is not null");
+ }
+
+ Button replyButton = (Button)getActivity().findViewById(R.id.replyButton);
+ if(replyButton!=null) {
+ replyButton.setEnabled(true);
+ }
+
+ replyButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Toast.makeText(getActivity(),"PRESSED REPLY",Toast.LENGTH_SHORT).show();
+ Intent toComposeIntent = new Intent(getActivity(), ComposeActivity.class);
+ toComposeIntent.putExtra("DRAFT",mEmail.getTheID());
+ startActivity(toComposeIntent);
+
+ }
+ });
+ /*Activity activity = this.getActivity();
+ CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
+ if (appBarLayout != null) {
+ appBarLayout.setTitle(mItem.content);
+ }*/
+ }
+
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View rootView = inflater.inflate(R.layout.email_detail, container, false);
+
+ // Show the dummy content as text in a TextView.
+ if (mEmail != null) {
+ Log.d("emailDetailFragment", "email is not null, aboout to call webview");
+ // ((WebView) rootView.findViewById(R.id.web_view)).loadData(mEmail.getBodyData(), "text/html", null);
+
+ if(mEmail.getType().equals("html")) {
+ Log.d("EmailDetailFragment","emailDetailFragment is html");
+ WebView webView = (WebView) rootView.findViewById((R.id.web_view));
+ webView.setVisibility(View.VISIBLE);
+ TextView textView = (TextView)rootView.findViewById(R.id.email_TextView);
+ textView.setVisibility(View.GONE);
+ webView.loadData(mEmail.getBodyData(), "text/html", null);
+ if (webView == null) {
+ Log.d("emailDetailFragment", "webview is null");
+ }
+ }else{
+ WebView webView = (WebView) rootView.findViewById((R.id.web_view));
+ webView.setVisibility(View.GONE);
+ Log.d("EmailDetailFragment", "emailDetailFragment is text");
+ Log.d("EmailDetailFragment","Body data "+mEmail.getBodyData());
+ TextView textView = (TextView)rootView.findViewById(R.id.email_TextView);
+ textView.setVisibility(View.VISIBLE);
+ textView.setText(mEmail.getBodyData());
+ int red = (int)(Math.random()*255)+1;
+ int blue = (int)(Math.random()*255)+1;
+ int green = (int)(Math.random()*255)+1;
+ textView.setBackgroundColor(Color.rgb(red,blue,green));
+ }
+// //TextView backUpTextView =(TextView) rootView.findViewById(R.id.backup_textView);
+// int red = (int)(Math.random()*255)+1;
+// int blue = (int)(Math.random()*255)+1;
+// int green = (int)(Math.random()*255)+1;
+// //rootView.setBackgroundColor(Color.rgb(red, blue, green));
+// webView.setBackgroundColor(Color.rgb(red, blue, green));
+ }
+
+ return rootView;
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/EMailManager.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/EMailManager.java
new file mode 100644
index 0000000..d02e141
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/EMailManager.java
@@ -0,0 +1,102 @@
+package com.example.gmailquickstart.emailStuff;
+
+import android.util.Log;
+
+import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
+
+import java.util.ArrayList;
+
+/**
+ * Created by nat on 2/26/16.
+ */
+public class EMailManager {
+
+ private static EMailManager mInstance;
+
+ private GoogleAccountCredential mCredential;
+ private String mUserEmail = "";
+
+ public String getUserEmail() {
+ return mUserEmail;
+ }
+
+
+
+ public GoogleAccountCredential getCredential() {
+ return mCredential;
+ }
+
+ public void setCredential(GoogleAccountCredential credential) {
+ mCredential = credential;
+ mUserEmail=mCredential.getSelectedAccountName();
+
+ }
+
+ private ArrayListmEmails;
+ private long mLastUpdated=0;
+
+ public static EMailManager getInstance() {
+ if (mInstance == null) {
+ mInstance = new EMailManager();
+ }
+ return mInstance;
+ }
+
+
+ private EMailManager(){
+ mEmails = new ArrayList<>();
+ }
+
+ public boolean isTimeToUpdate(){
+ long currentTime = System.currentTimeMillis();
+ if(currentTime-mLastUpdated<=120000){
+ Log.d("EmailManager","Recommended not to update as its been less than two minutes since last update");
+ return false;
+ }
+ Log.d("EmailManager","Recommended to UPDATE as its been more than two minutes since last update");
+ return true;
+ }
+ public boolean startUpdate(){
+ if(isTimeToUpdate()==false){
+ return false;
+ }
+ clearEmails();
+ return true;
+ }
+
+
+ public void endUpdate(){
+ mLastUpdated = System.currentTimeMillis();
+ }
+ public void clearEmails(){
+ mEmails.clear();
+ }
+ public void addEmail(Email email){
+
+ mEmails.add(email);
+ }
+
+ public Email getEmailByID(String id){
+ for(Email message:mEmails){
+ if(message.getTheID().equals(id)){
+
+ return message;
+ }
+ }
+ return null;
+ }
+ public ArrayListgetAllEmails(){
+ return mEmails;
+ }
+
+ public void printAllToLog(){
+ if(mEmails.size()==0){
+ Log.d("PRINT NO EMAILS","no emails here");
+ }else{
+ Log.d("PRINT ALL EMAILS","THE NUMBER OF mEmails is "+mEmails.size());
+ }
+ for(Email mail: mEmails){
+ Log.d("PRINT ALL MAIL ",mail.getSnippet()+" "+mail.getTheID());
+ }
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/Email.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/Email.java
new file mode 100644
index 0000000..6ee65f4
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/Email.java
@@ -0,0 +1,89 @@
+package com.example.gmailquickstart.emailStuff;
+
+import java.util.ArrayList;
+
+/**
+ * Created by nat on 2/26/16.
+ */
+public class Email {
+ private String mSnippet;
+ private String mTheID;
+ private String mSubject;
+ private String mBodyData;
+ private ArrayList mToData;
+ private String mFromData;
+
+ public String getType() {
+ return mType;
+ }
+
+ public void setType(String type) {
+ mType = type;
+ }
+
+ private String mType;
+
+ public boolean isDraft() {
+ return mIsDraft;
+ }
+
+ public void setIsDraft(boolean isDraft) {
+ mIsDraft = isDraft;
+ }
+
+ private boolean mIsDraft;
+
+
+ public ArrayList getToData() {
+ return mToData;
+ }
+
+ public void addTo(String toData) {
+ mToData.add(toData);
+ }
+
+ public String getFromData() {
+ return mFromData;
+ }
+
+ public void setFromData(String fromData) {
+ mFromData = fromData;
+ }
+
+ public String getBodyData() {
+ return mBodyData;
+ }
+
+ public void setBodyData(String bodyData) {
+ mBodyData = bodyData;
+ }
+
+ public String getSubject() {
+ return mSubject;
+ }
+
+ public void setSubject(String subject) {
+ mSubject = subject;
+ }
+
+ public String getSnippet() {
+ return mSnippet;
+ }
+
+ public void setSnippet(String snippet) {
+ mSnippet = snippet;
+ }
+
+ public String getTheID() {
+ return mTheID;
+ }
+
+ public void setTheID(String theID) {
+ mTheID = theID;
+ }
+
+
+ public Email(){
+ mToData = new ArrayList<>();
+ }
+}
diff --git a/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/SendEmailThread.java b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/SendEmailThread.java
new file mode 100644
index 0000000..af5f539
--- /dev/null
+++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/SendEmailThread.java
@@ -0,0 +1,231 @@
+package com.example.gmailquickstart.emailStuff;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.os.AsyncTask;
+import android.util.Log;
+
+import com.example.gmailquickstart.EmailListActivity;
+import com.google.api.client.extensions.android.http.AndroidHttp;
+import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
+import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
+import com.google.api.client.http.HttpTransport;
+import com.google.api.client.json.JsonFactory;
+import com.google.api.client.json.jackson2.JacksonFactory;
+import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
+import com.google.api.services.gmail.Gmail;
+import com.google.api.services.gmail.model.Draft;
+import com.google.api.services.gmail.model.Message;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+/**
+ * Created by nat on 2/28/16.
+ */
+public class SendEmailThread extends AsyncTask {
+
+ private com.google.api.services.gmail.Gmail mService = null;
+ private Exception mLastError = null;
+ private Context mContext;
+
+ public SendEmailThread(GoogleAccountCredential credential,Context context) {
+ mContext=context;
+ HttpTransport transport = AndroidHttp.newCompatibleTransport();
+ JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
+ mService = new com.google.api.services.gmail.Gmail.Builder(
+ transport, jsonFactory, credential)
+ .setApplicationName("GEE MAIL")
+ .build();
+ }
+ @Override
+ protected Boolean doInBackground(Email... params) {
+ if(params[0]==null){
+ return false;
+ }
+ Email emailToBeSent = (Email)params[0];
+
+ Log.d("SendEmailThread", "sending email with following info FROM:" + emailToBeSent.getFromData() + "\r\n SUBJECT" + emailToBeSent.getSnippet() + "\r\n" + "BODY " + emailToBeSent.getBodyData());
+
+ try{
+ MimeMessage mimeMessage = createEmail(emailToBeSent.getToData().get(0),emailToBeSent.getFromData(),emailToBeSent.getSubject(),emailToBeSent.getBodyData());
+ createMessageWithEmail(mimeMessage);
+ if(emailToBeSent.isDraft()){
+ createDraft(mService,"me",mimeMessage);
+ }else {
+ sendMessage(mService, "me", mimeMessage);
+ }
+ }catch(MessagingException me){
+ me.printStackTrace();
+ return false;
+ }catch(IOException ioe){
+ ioe.printStackTrace();
+ return false;
+ }
+ //sendMail(mService, emailToBeSent.getFromData(), emailToBeSent.getToData(), emailToBeSent.getSubject(), emailToBeSent.getBodyData());
+ return true;
+ }
+
+ @Override
+ protected void onPostExecute(Boolean result) {
+ super.onPostExecute(result);
+
+
+ Activity a = (Activity)mContext;
+ Intent intentToMessageMain = new Intent();
+ intentToMessageMain.putExtra("RESULT_OF_COMPOSE",result);
+ a.setResult(EmailListActivity.COMPOSE_EMAIL,intentToMessageMain);
+ a.finish();
+ }
+
+ @Override
+ protected void onPreExecute() {
+ super.onPreExecute();
+ }
+
+ public static boolean sendMail(Gmail service, String from, List to, String title, String body) {
+ if (service == null) {
+ return false;
+ }
+ Message message = new Message();
+
+ StringBuilder builder = new StringBuilder();
+ builder.append("From: ");
+ builder.append(from);
+ builder.append("\nTo: ");
+ if (to != null) {
+ int toSize = to.size();
+ for (int i = 0; i < toSize; i++) {
+ String tmp = to.get(i).replace(",", "");
+ builder.append(tmp);
+ if (i < toSize - 1) {
+ builder.append(", ");
+ }
+ }
+ }
+ builder.append("\nDate: ");
+ SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
+ String date = sdf.format(new Date());
+ builder.append(date);
+ builder.append("\nMIME-Version: 1.0\nSubject: =?ISO-2022-JP?B?");
+ if (title != null) {
+ try {
+ builder.append(Base64.encodeBase64URLSafeString(title.getBytes("ISO-2022-JP")));
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ }
+ builder.append("?=");
+ builder.append("\nContent-Type: text/plain; charset=ISO-2022-JP;");
+ builder.append("\nContent-Transfer-Encoding: 7bit");
+ builder.append("\n\n");
+ builder.append(body);
+
+ String encodedEmail = Base64.encodeBase64URLSafeString(builder.toString().getBytes());
+
+ message.setRaw(encodedEmail);
+
+ boolean result = false;
+
+ try {
+ message = service.users().messages().send("me", message).execute();
+ result = true;
+ } catch (UserRecoverableAuthIOException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ return result;
+ }
+ /**
+ * Create a MimeMessage using the parameters provided.
+ *
+ * @param to Email address of the receiver.
+ * @param from Email address of the sender, the mailbox account.
+ * @param subject Subject of the email.
+ * @param bodyText Body text of the email.
+ * @return MimeMessage to be used to send email.
+ * @throws MessagingException
+ */
+ public MimeMessage createEmail(String to, String from, String subject,
+ String bodyText) throws MessagingException {
+ Log.d("SendEmailThread", "inside createEmail");
+ Log.d("SendEmailThread","to "+to);
+ Log.d("SendEmailThread", "from " + from);
+ Log.d("SendEmailThread", "bodyText " + bodyText);
+ Properties props = new Properties();
+ Session session = Session.getDefaultInstance(props, null);
+
+ MimeMessage email = new MimeMessage(session);
+ InternetAddress tAddress = new InternetAddress(to);
+ InternetAddress fAddress = new InternetAddress(from);
+
+ email.setFrom(new InternetAddress(from));
+ email.addRecipient(javax.mail.Message.RecipientType.TO,
+ new InternetAddress(to));
+ email.setSubject(subject);
+ email.setText(bodyText);
+ return email;
+ }
+ /**
+ * Create a Message from an email
+ *
+ * @param email Email to be set to raw of message
+ * @return Message containing base64url encoded email.
+ * @throws IOException
+ * @throws MessagingException
+ */
+ public Message createMessageWithEmail(MimeMessage email)
+ throws MessagingException, IOException {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ email.writeTo(bytes);
+ String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
+ Message message = new Message();
+ message.setRaw(encodedEmail);
+ return message;
+ }
+ /**
+ * Send an email from the user's mailbox to its recipient.
+ *
+ * @param service Authorized Gmail API instance.
+ * @param userId User's email address. The special value "me"
+ * can be used to indicate the authenticated user.
+ * @param email Email to be sent.
+ * @throws MessagingException
+ * @throws IOException
+ */
+ public void sendMessage(Gmail service, String userId, MimeMessage email)
+ throws MessagingException, IOException {
+ Message message = createMessageWithEmail(email);
+ message = service.users().messages().send(userId, message).execute();
+
+ System.out.println("Message id: " + message.getId());
+ System.out.println(message.toPrettyString());
+ }
+
+ public Draft createDraft(Gmail service, String userId, MimeMessage email)
+ throws MessagingException, IOException {
+ Message message = createMessageWithEmail(email);
+ Draft draft = new Draft();
+ draft.setMessage(message);
+ draft = service.users().drafts().create(userId, draft).execute();
+
+ System.out.println("draft id: " + draft.getId());
+ System.out.println(draft.toPrettyString());
+ return draft;
+ }
+
+}
diff --git a/GmailQuickStart/app/src/main/res/drawable/back.xml b/GmailQuickStart/app/src/main/res/drawable/back.xml
new file mode 100644
index 0000000..2674c66
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/drawable/back.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/res/drawable/border_set.xml b/GmailQuickStart/app/src/main/res/drawable/border_set.xml
new file mode 100644
index 0000000..186113d
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/drawable/border_set.xml
@@ -0,0 +1,45 @@
+
+
+ -
+
+
+
+
+
+
+
+
+
+ -
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/res/layout-w900dp/email_list.xml b/GmailQuickStart/app/src/main/res/layout-w900dp/email_list.xml
new file mode 100644
index 0000000..c34984c
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout-w900dp/email_list.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/activity_compose.xml b/GmailQuickStart/app/src/main/res/layout/activity_compose.xml
new file mode 100644
index 0000000..6732491
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/activity_compose.xml
@@ -0,0 +1,97 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/activity_email_detail.xml b/GmailQuickStart/app/src/main/res/layout/activity_email_detail.xml
new file mode 100644
index 0000000..729ea21
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/activity_email_detail.xml
@@ -0,0 +1,77 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/activity_email_list.xml b/GmailQuickStart/app/src/main/res/layout/activity_email_list.xml
new file mode 100644
index 0000000..004d4a9
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/activity_email_list.xml
@@ -0,0 +1,77 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/activity_main.xml b/GmailQuickStart/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..a4807f7
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/email_detail.xml b/GmailQuickStart/app/src/main/res/layout/email_detail.xml
new file mode 100644
index 0000000..09d8849
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/email_detail.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/email_list.xml b/GmailQuickStart/app/src/main/res/layout/email_list.xml
new file mode 100644
index 0000000..89cd04a
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/email_list.xml
@@ -0,0 +1,13 @@
+
+
diff --git a/GmailQuickStart/app/src/main/res/layout/email_list_content.xml b/GmailQuickStart/app/src/main/res/layout/email_list_content.xml
new file mode 100644
index 0000000..6e3512c
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/layout/email_list_content.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/res/menu/options_menu.xml b/GmailQuickStart/app/src/main/res/menu/options_menu.xml
new file mode 100644
index 0000000..243b354
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/menu/options_menu.xml
@@ -0,0 +1,9 @@
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/main/res/mipmap-hdpi/ic_launcher.png b/GmailQuickStart/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..cde69bc
Binary files /dev/null and b/GmailQuickStart/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/GmailQuickStart/app/src/main/res/mipmap-mdpi/ic_launcher.png b/GmailQuickStart/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..c133a0c
Binary files /dev/null and b/GmailQuickStart/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/GmailQuickStart/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/GmailQuickStart/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..bfa42f0
Binary files /dev/null and b/GmailQuickStart/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/GmailQuickStart/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/GmailQuickStart/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..324e72c
Binary files /dev/null and b/GmailQuickStart/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/GmailQuickStart/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/GmailQuickStart/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..aee44e1
Binary files /dev/null and b/GmailQuickStart/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/GmailQuickStart/app/src/main/res/values-v21/styles.xml b/GmailQuickStart/app/src/main/res/values-v21/styles.xml
new file mode 100644
index 0000000..251fb9f
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values-v21/styles.xml
@@ -0,0 +1,9 @@
+>
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/values-w820dp/dimens.xml b/GmailQuickStart/app/src/main/res/values-w820dp/dimens.xml
new file mode 100644
index 0000000..63fc816
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values-w820dp/dimens.xml
@@ -0,0 +1,6 @@
+
+
+ 64dp
+
diff --git a/GmailQuickStart/app/src/main/res/values/colors.xml b/GmailQuickStart/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..3ab3e9c
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #3F51B5
+ #303F9F
+ #FF4081
+
diff --git a/GmailQuickStart/app/src/main/res/values/dimens.xml b/GmailQuickStart/app/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..3aca65d
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values/dimens.xml
@@ -0,0 +1,9 @@
+
+
+ 16dp
+ 16dp
+ 16dp
+ 200dp
+ 200dp
+ 16dp
+
diff --git a/GmailQuickStart/app/src/main/res/values/strings.xml b/GmailQuickStart/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..7a106df
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values/strings.xml
@@ -0,0 +1,5 @@
+
+ GmailQuickStart
+ emails
+ email Detail
+
diff --git a/GmailQuickStart/app/src/main/res/values/styles.xml b/GmailQuickStart/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..177cefc
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/values/styles.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/GmailQuickStart/app/src/main/res/xml/searchable.xml b/GmailQuickStart/app/src/main/res/xml/searchable.xml
new file mode 100644
index 0000000..0208c26
--- /dev/null
+++ b/GmailQuickStart/app/src/main/res/xml/searchable.xml
@@ -0,0 +1,5 @@
+
+
+
\ No newline at end of file
diff --git a/GmailQuickStart/app/src/test/java/com/example/gmailquickstart/ExampleUnitTest.java b/GmailQuickStart/app/src/test/java/com/example/gmailquickstart/ExampleUnitTest.java
new file mode 100644
index 0000000..9204b10
--- /dev/null
+++ b/GmailQuickStart/app/src/test/java/com/example/gmailquickstart/ExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.example.gmailquickstart;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * To work on unit tests, switch the Test Artifact in the Build Variants view.
+ */
+public class ExampleUnitTest {
+ @Test
+ public void addition_isCorrect() throws Exception {
+ assertEquals(4, 2 + 2);
+ }
+}
\ No newline at end of file
diff --git a/GmailQuickStart/build.gradle b/GmailQuickStart/build.gradle
new file mode 100644
index 0000000..e0b366a
--- /dev/null
+++ b/GmailQuickStart/build.gradle
@@ -0,0 +1,23 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.5.0'
+
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
diff --git a/GmailQuickStart/gradle.properties b/GmailQuickStart/gradle.properties
new file mode 100644
index 0000000..1d3591c
--- /dev/null
+++ b/GmailQuickStart/gradle.properties
@@ -0,0 +1,18 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
\ No newline at end of file
diff --git a/GmailQuickStart/gradle/wrapper/gradle-wrapper.jar b/GmailQuickStart/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..05ef575
Binary files /dev/null and b/GmailQuickStart/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/GmailQuickStart/gradle/wrapper/gradle-wrapper.properties b/GmailQuickStart/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..f23df6e
--- /dev/null
+++ b/GmailQuickStart/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Wed Oct 21 11:34:03 PDT 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
diff --git a/GmailQuickStart/gradlew b/GmailQuickStart/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/GmailQuickStart/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/GmailQuickStart/gradlew.bat b/GmailQuickStart/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/GmailQuickStart/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/GmailQuickStart/settings.gradle b/GmailQuickStart/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/GmailQuickStart/settings.gradle
@@ -0,0 +1 @@
+include ':app'