From 8fbbd373ef0a596f4f49c06d7aac85a20f03ee21 Mon Sep 17 00:00:00 2001 From: programmingnat Date: Sun, 28 Feb 2016 12:39:23 -0500 Subject: [PATCH 1/6] Basic functions working, get emails and send emails --- GmailQuickStart/.gitignore | 8 + GmailQuickStart/.idea/.name | 1 + GmailQuickStart/.idea/compiler.xml | 22 + .../.idea/copyright/profiles_settings.xml | 3 + GmailQuickStart/.idea/gradle.xml | 18 + GmailQuickStart/.idea/misc.xml | 62 ++ GmailQuickStart/.idea/modules.xml | 9 + GmailQuickStart/.idea/runConfigurations.xml | 12 + GmailQuickStart/.idea/vcs.xml | 6 + GmailQuickStart/app/.gitignore | 1 + GmailQuickStart/app/build.gradle | 38 ++ GmailQuickStart/app/proguard-rules.pro | 17 + .../gmailquickstart/ApplicationTest.java | 13 + .../app/src/main/AndroidManifest.xml | 45 ++ .../gmailquickstart/ComposeActivity.java | 61 ++ .../gmailquickstart/EmailListActivity.java | 556 ++++++++++++++++++ .../example/gmailquickstart/MainActivity.java | 438 ++++++++++++++ .../gmailquickstart/dummy/DummyContent.java | 72 +++ .../gmailquickstart/emailDetailActivity.java | 81 +++ .../gmailquickstart/emailDetailFragment.java | 83 +++ .../emailStuff/EMailManager.java | 100 ++++ .../gmailquickstart/emailStuff/Email.java | 69 +++ .../emailStuff/SendEmailThread.java | 131 +++++ .../app/src/main/res/drawable/back.xml | 4 + .../app/src/main/res/drawable/border_set.xml | 45 ++ .../src/main/res/layout-w900dp/email_list.xml | 38 ++ .../src/main/res/layout/activity_compose.xml | 97 +++ .../main/res/layout/activity_email_detail.xml | 78 +++ .../main/res/layout/activity_email_list.xml | 43 ++ .../app/src/main/res/layout/activity_main.xml | 17 + .../app/src/main/res/layout/email_detail.xml | 20 + .../app/src/main/res/layout/email_list.xml | 13 + .../main/res/layout/email_list_content.xml | 20 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 3418 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 2206 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 4842 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 7718 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 10486 bytes .../app/src/main/res/values-v21/styles.xml | 9 + .../app/src/main/res/values-w820dp/dimens.xml | 6 + .../app/src/main/res/values/colors.xml | 6 + .../app/src/main/res/values/dimens.xml | 9 + .../app/src/main/res/values/strings.xml | 5 + .../app/src/main/res/values/styles.xml | 20 + .../gmailquickstart/ExampleUnitTest.java | 15 + GmailQuickStart/build.gradle | 23 + GmailQuickStart/gradle.properties | 18 + .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 53637 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 + GmailQuickStart/gradlew | 160 +++++ GmailQuickStart/gradlew.bat | 90 +++ GmailQuickStart/settings.gradle | 1 + 52 files changed, 2589 insertions(+) create mode 100644 GmailQuickStart/.gitignore create mode 100644 GmailQuickStart/.idea/.name create mode 100644 GmailQuickStart/.idea/compiler.xml create mode 100644 GmailQuickStart/.idea/copyright/profiles_settings.xml create mode 100644 GmailQuickStart/.idea/gradle.xml create mode 100644 GmailQuickStart/.idea/misc.xml create mode 100644 GmailQuickStart/.idea/modules.xml create mode 100644 GmailQuickStart/.idea/runConfigurations.xml create mode 100644 GmailQuickStart/.idea/vcs.xml create mode 100644 GmailQuickStart/app/.gitignore create mode 100644 GmailQuickStart/app/build.gradle create mode 100644 GmailQuickStart/app/proguard-rules.pro create mode 100644 GmailQuickStart/app/src/androidTest/java/com/example/gmailquickstart/ApplicationTest.java create mode 100644 GmailQuickStart/app/src/main/AndroidManifest.xml create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/ComposeActivity.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/EmailListActivity.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/MainActivity.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/dummy/DummyContent.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailActivity.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailFragment.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/EMailManager.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/Email.java create mode 100644 GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/SendEmailThread.java create mode 100644 GmailQuickStart/app/src/main/res/drawable/back.xml create mode 100644 GmailQuickStart/app/src/main/res/drawable/border_set.xml create mode 100644 GmailQuickStart/app/src/main/res/layout-w900dp/email_list.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/activity_compose.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/activity_email_detail.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/activity_email_list.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/activity_main.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/email_detail.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/email_list.xml create mode 100644 GmailQuickStart/app/src/main/res/layout/email_list_content.xml create mode 100644 GmailQuickStart/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 GmailQuickStart/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 GmailQuickStart/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 GmailQuickStart/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 GmailQuickStart/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 GmailQuickStart/app/src/main/res/values-v21/styles.xml create mode 100644 GmailQuickStart/app/src/main/res/values-w820dp/dimens.xml create mode 100644 GmailQuickStart/app/src/main/res/values/colors.xml create mode 100644 GmailQuickStart/app/src/main/res/values/dimens.xml create mode 100644 GmailQuickStart/app/src/main/res/values/strings.xml create mode 100644 GmailQuickStart/app/src/main/res/values/styles.xml create mode 100644 GmailQuickStart/app/src/test/java/com/example/gmailquickstart/ExampleUnitTest.java create mode 100644 GmailQuickStart/build.gradle create mode 100644 GmailQuickStart/gradle.properties create mode 100644 GmailQuickStart/gradle/wrapper/gradle-wrapper.jar create mode 100644 GmailQuickStart/gradle/wrapper/gradle-wrapper.properties create mode 100755 GmailQuickStart/gradlew create mode 100644 GmailQuickStart/gradlew.bat create mode 100644 GmailQuickStart/settings.gradle 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..cca2cda --- /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/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..9a70df4 --- /dev/null +++ b/GmailQuickStart/app/build.gradle @@ -0,0 +1,38 @@ +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' + } + } +} + +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' +} 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..06cfd58 --- /dev/null +++ b/GmailQuickStart/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..199ba90 --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/ComposeActivity.java @@ -0,0 +1,61 @@ +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; + +public class ComposeActivity extends AppCompatActivity { + + String mUser=""; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_compose); + + EMailManager emailManager = EMailManager.getInstance(); + mUser=emailManager.getUserEmail(); + + EditText fromEditText = (EditText)findViewById(R.id.from_edit_text); + fromEditText.setText(mUser); + + Button sendEmailButton = (Button)findViewById(R.id.sendTheMessageButton); + sendEmailButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + EditText toEditText = (EditText)findViewById(R.id.to_edit_text); + String theToField=toEditText.getText().toString(); + String[] recipients = theToField.split(","); + + EditText fromEditText = (EditText)findViewById(R.id.from_edit_text); + String theFromField=fromEditText.getText().toString(); + + EditText subjectEditText = (EditText)findViewById(R.id.subject_edit_text); + String subjectField=subjectEditText.getText().toString(); + + EditText theBodyEditText = (EditText)findViewById(R.id.theMessageBody); + String bodyField=theBodyEditText.getText().toString(); + + Email emailToSend = new Email(); + for(int i=0;i())); + } + + //OVERIDDEN METHODS BELOW + /** + * 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 { + 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 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); + } + //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) { + if (mTwoPane) { + 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 { + 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 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 + ArrayList theLabels = new ArrayList<>(); + theLabels.add("INBOX"); + theLabels.add("CATEGORY_PERSONAL"); + //ListMessagesResponse response =mService.users().messages().list(user).execute(); + ListMessagesResponse response = mService.users().messages().list(user).setLabelIds(theLabels).setIncludeSpamTrash(false).setMaxResults(20L).execute(); + //ListMessagesResponse response = mService.users().messages().list(user).setQ("google").execute(); + + EMailManager emailManager = EMailManager.getInstance(); + emailManager.startUpdate(); + StringBuilder builder = new StringBuilder(); + String body2=" "; + String bod=" "; + for (Message message : response.getMessages()) { + + Message actualMessage = mService.users().messages().get(user, message.getId()).execute(); + + + + + + + Log.d("EmalListActivity"," body "+bod); + //actualMessage.getPayload().getBody(); + //Log.d("MainActivity", "stuff: " + actualMessage.getPayload().getHeaders()); + ArrayList 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"); + + String htmlData=""; + String plainData=""; + for(MessagePart m : messageParts){ + if(m.getMimeType().contains("multipart")){ + Log.d("EmailListActivity","This message contains multipart"); + ArrayListparts = (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); + } + } + + } + + //Log.d("EmailListActivity","MessagePart "+m.getPartId()+" "+m.getMimeType()); + + //MessagePartBody body = m.getBody(); + //if(body==null){ + // continue; + //} + //byte[] data=body.decodeData(); + + //String encodedData = body.getData(); + // byte[] data = Base64.decodeBase64(encodedData); + //String result = new String(Base64.decodeBase64(encodedData)); + // String content=new String(data); + // Log.d("EmailListActivity","the content "+content); + + + } + // byte[] b = actualMessage.decodeRaw(); + //String str = new String(b, Charset.forName("UTF-8")); + //Log.d("MainActivity",str); + + Email newEmail = new Email(); + newEmail.setSnippet(actualMessage.getSnippet()); + newEmail.setTheID(actualMessage.getId()); + newEmail.setSubject(emailSubject); + newEmail.setBodyData(htmlData); + 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(); + + //send email + //Gmail service, String from, List to, String title, String body + //ArrayListtoPerson = new ArrayList<>(); + //toPerson.add("wctygret@gmail.com"); + //sendMail(mService,"nat2014111@gmail.com",toPerson,"TEST","This is the body of the email"); + //RecyclerView recyclerView = (RecyclerView)emailListActivity.this.findViewById(R.id.email_list); + //recyclerView.setAdapter(); + return labels; + } + + + + @Override + protected void onPreExecute() { + //mOutputText.setText(""); + mProgress.show(); + } + + @Override + protected void onPostExecute(List output) { + 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..41fa28d --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailActivity.java @@ -0,0 +1,81 @@ +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.widget.Toolbar; +import android.view.View; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.app.ActionBar; +import android.view.MenuItem; + +/** + * 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..ca0464c --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailDetailFragment.java @@ -0,0 +1,83 @@ +package com.example.gmailquickstart; + +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 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"); + } + + /*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) { + ((WebView) rootView.findViewById(R.id.web_view)).loadData(mEmail.getBodyData(),"text/html",null); + } + + 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..e23a876 --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/EMailManager.java @@ -0,0 +1,100 @@ +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(); + } + private 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..09fd70b --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/Email.java @@ -0,0 +1,69 @@ +package com.example.gmailquickstart.emailStuff; + +import java.util.ArrayList; + +/** + * Created by nat on 2/26/16. + */ +public class Email { + String mSnippet; + String mTheID; + String mSubject; + String mBodyData; + ArrayList mToData; + String mFromData; + + + 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..160af95 --- /dev/null +++ b/GmailQuickStart/app/src/main/java/com/example/gmailquickstart/emailStuff/SendEmailThread.java @@ -0,0 +1,131 @@ +package com.example.gmailquickstart.emailStuff; + +import android.app.Activity; +import android.content.Context; +import android.os.AsyncTask; +import android.util.Log; +import android.widget.Toast; + +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.Message; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * 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 = params[0]; + + Log.d("SendEmailThread","sending email with following info FROM:"+emailToBeSent.getFromData()+"\r\n SUBJECT"+emailToBeSent.getSnippet()+"\r\n"+"BODY "+emailToBeSent.getBodyData()); + sendMail(mService, emailToBeSent.getFromData(), emailToBeSent.getToData(), emailToBeSent.getSubject(), emailToBeSent.getBodyData()); + return true; + } + + @Override + protected void onPostExecute(Boolean result) { + super.onPostExecute(result); + if(result){ + + }else{ + Toast.makeText(mContext,"Unable to send the email",Toast.LENGTH_LONG).show(); + } + + Activity a = (Activity)mContext; + 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; + } + + +} 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..985c6fb --- /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 @@ + + + + + + + + +