├── .gitignore ├── .idea ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── encodings.xml ├── gradle.xml ├── misc.xml └── vcs.xml ├── LICENSE ├── README.md ├── androidsendgrid ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── uk │ │ │ └── co │ │ │ └── jakebreen │ │ │ └── sendgridandroid │ │ │ ├── ErrorParser.java │ │ │ ├── FileEncoder.java │ │ │ ├── SendGrid.java │ │ │ ├── SendGridCall.java │ │ │ ├── SendGridMail.java │ │ │ ├── SendGridMailBody.java │ │ │ ├── SendGridResponse.java │ │ │ ├── SendTask.java │ │ │ └── SendTaskAsync.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ ├── java │ └── uk │ │ └── co │ │ └── jakebreen │ │ └── sendgridandroid │ │ ├── SendGridMailBodyTest.java │ │ └── SendGridTest.java │ └── res │ └── json │ ├── email │ ├── email_content_empty │ ├── email_content_html_empty │ ├── email_content_plain_empty │ ├── email_dynamic_template │ ├── email_unsubscribe_groups │ ├── emails_array │ └── emails_tracking_settings_enabled ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images └── heading-image.jpg ├── settings.gradle └── testapp ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main ├── AndroidManifest.xml ├── java └── uk │ └── co │ └── jakebreen │ └── sendgridandroid │ └── testapp │ ├── FileUtil.java │ └── MainActivity.java └── res ├── drawable-v24 └── ic_launcher_foreground.xml ├── drawable └── ic_launcher_background.xml ├── layout └── activity_main.xml ├── mipmap-anydpi-v26 ├── ic_launcher.xml └── ic_launcher_round.xml ├── mipmap-hdpi ├── ic_launcher.png └── ic_launcher_round.png ├── mipmap-mdpi ├── ic_launcher.png └── ic_launcher_round.png ├── mipmap-xhdpi ├── ic_launcher.png └── ic_launcher_round.png ├── mipmap-xxhdpi ├── ic_launcher.png └── ic_launcher_round.png ├── mipmap-xxxhdpi ├── ic_launcher.png └── ic_launcher_round.png └── values ├── colors.xml ├── strings.xml └── styles.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .idea 15 | gradle.properties 16 | /.idea/ 17 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 HiHi Ltd 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![](https://jitpack.io/v/jakebreen/android-sendgrid.svg)](https://jitpack.io/#jakebreen/android-sendgrid) 2 | 3 | ![header](https://github.com/Jakebreen/android-sendgrid/blob/master/images/heading-image.jpg) 4 | 5 | # android-sendgrid 6 | A simplified Android email library utilising SendGrid's v3 API that targets minSdkVersion 16. 7 | 8 | Use with JitPack and implement in your app 9 | ``` 10 | allprojects { 11 | repositories { 12 | ... 13 | maven { url "https://jitpack.io" } 14 | } 15 | } 16 | 17 | dependencies { 18 | implementation 'com.github.jakebreen:android-sendgrid:1.3.1' 19 | } 20 | ``` 21 | 22 | # How to use 23 | Create an instance of the SendGrid library tied to your API key. 24 | ``` 25 | SendGrid sendGrid = SendGrid.create(@NonNull String apiKey) 26 | ``` 27 | 28 | Create a SendGridMail and provide the required attributes. 29 | ``` 30 | SendGridMail mail = new SendGridMail() 31 | mail.addRecipient(@NonNull String email, @Nullable String name) 32 | mail.setFrom(@NonNull String email, @Nullable String name) 33 | mail.setSubject(@NonNull String subject) 34 | mail.setContent(@NonNull String body) 35 | ``` 36 | Set a plain text or a html text content body, when using a template neither of these content variables need to be set. 37 | ``` 38 | mail.setContent(@NonNull String body) 39 | mail.setHtmlContent(@NonNull String body) 40 | ``` 41 | 42 | Send a mail with the library's SendTask. 43 | ``` 44 | SendTask task = new SendTask(sendGrid); 45 | SendGridResponse response = task.send(mail); 46 | ``` 47 | 48 | Send a mail with RxJava. 49 | ``` 50 | Single.fromCallable(sendGrid.send(mail)) 51 | .subscribeOn(Schedulers.io()) 52 | .subscribe(response -> { 53 | if (response.isSuccessful()) { 54 | // ... 55 | } 56 | } 57 | ); 58 | ``` 59 | 60 | Send requests return a SendGridResponse that contains the success state of the request and the associated HTTP response code. 61 | A failed request will contain the error message from the API. 62 | ``` 63 | response.isSuccessful() 64 | response.getCode() 65 | response.getErrorMessage() 66 | ``` 67 | 68 | Additional SendGridMail methods that aren't required to send an email include templates, tracking, carbon copies, attachments and others 69 | ``` 70 | mail.addAttachment(@NonNull File file) 71 | mail.addAttachment(@NonNull Uri uri) 72 | mail.addRecipientCarbonCopy(@NonNull String email, @Nullable String name) 73 | mail.addRecipientBlindCarbonCopy(@NonNull String email, @Nullable String name) 74 | mail.setReplyTo(@NonNull String email, @Nullable String name) 75 | mail.setSendAt(@NonNull int sendAt) 76 | mail.setClickTrackingEnabled(@NonNull Boolean enabled) 77 | mail.setOpenTrackingEnabled(@NonNull Boolean enabled) 78 | mail.setSubscriptionTrackingEnabled(@NonNull Boolean enabled) 79 | mail.setUnsubscribeGroupId(@NonNull int groupId) 80 | mail.setUnsubscribeGroupIds(@NonNull int groupId, List groupIds) 81 | ``` 82 | 83 | Transactional email templates and custom data can be applied to the SendGridMail in the form of a JSONObject structured into key/value pairs 84 | ``` 85 | mail.setTemplateId(@NonNull String templateId) 86 | mail.setDynamicTemplateData(@NonNull JSONObject jsonObject) 87 | 88 | // JSONObject structured into key/value pairs 89 | final JSONObject templateData = new JSONObject(); 90 | templateData.put("forename", "Jane"); 91 | templateData.put("surname", "Doe"); 92 | templateData.put("message", "Hello, This is my email"); 93 | 94 | mail.setDynamicTemplateData(templateData) 95 | ``` 96 | 97 | # TestApp 98 | A test app included when cloning the library to test the library with file attachments, uses RxJava2. Feel free utilise this app. 99 | -------------------------------------------------------------------------------- /androidsendgrid/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | .idea -------------------------------------------------------------------------------- /androidsendgrid/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 32 5 | defaultConfig { 6 | minSdkVersion 16 7 | targetSdkVersion 32 8 | versionCode 5 9 | versionName = "1.4.0" 10 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 11 | } 12 | buildTypes { 13 | release { 14 | minifyEnabled false 15 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 16 | } 17 | } 18 | testOptions { 19 | unitTests.returnDefaultValues = true 20 | } 21 | sourceSets { 22 | test { 23 | resources.srcDirs += ['src/test/res'] 24 | } 25 | } 26 | } 27 | 28 | dependencies { 29 | implementation fileTree(dir: 'libs', include: ['*.jar']) 30 | implementation 'androidx.appcompat:appcompat:1.4.2' 31 | 32 | testImplementation 'junit:junit:4.13.2' 33 | testImplementation 'org.mockito:mockito-core:4.6.1' 34 | testImplementation 'org.json:json:20180813' 35 | } -------------------------------------------------------------------------------- /androidsendgrid/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/ErrorParser.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | class ErrorParser { 7 | 8 | private static final String KEY_ERRORS = "errors"; 9 | private static final String KEY_MESSAGE = "message"; 10 | 11 | static String parseError(String response) { 12 | try { 13 | return new JSONObject(response).getJSONArray(KEY_ERRORS).getJSONObject(0).get(KEY_MESSAGE).toString(); 14 | } catch (JSONException e) { 15 | e.printStackTrace(); 16 | return String.format("Error parsing error message: %s", e.getMessage()); 17 | } 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/FileEncoder.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import android.content.Context; 4 | import android.database.Cursor; 5 | import android.net.Uri; 6 | import android.provider.OpenableColumns; 7 | import android.util.Base64; 8 | import android.util.Base64OutputStream; 9 | 10 | import java.io.ByteArrayOutputStream; 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.io.OutputStream; 17 | 18 | class FileEncoder { 19 | 20 | private static final int BYTE_BUFFER_SIZE = 4 * 1024; 21 | 22 | static String encodeFileToBase64(File file) throws IOException { 23 | final InputStream inputStream = new FileInputStream(file.getAbsolutePath()); 24 | final ByteArrayOutputStream output = new ByteArrayOutputStream(); 25 | final Base64OutputStream output64 = new Base64OutputStream(output, Base64.NO_WRAP); 26 | 27 | final byte[] buffer = new byte[BYTE_BUFFER_SIZE]; 28 | int bytesRead; 29 | while ((bytesRead = inputStream.read(buffer)) != -1) { 30 | output64.write(buffer, 0, bytesRead); 31 | } 32 | 33 | output64.close(); 34 | return output.toString(); 35 | } 36 | 37 | static File uriToFile(Context context, Uri uri) throws IOException { 38 | final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); 39 | if (cursor == null) return null; 40 | 41 | final int indexName = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); 42 | cursor.moveToFirst(); 43 | 44 | final String fileName = cursor.getString(indexName); 45 | final File file = new File(context.getExternalCacheDir(), fileName); 46 | final OutputStream outputStream = new FileOutputStream(file); 47 | final InputStream inputStream = context.getContentResolver().openInputStream(uri); 48 | 49 | if (inputStream == null) return null; 50 | 51 | final byte[] buffer = new byte[BYTE_BUFFER_SIZE]; 52 | int bytesRead; 53 | while ((bytesRead = inputStream.read(buffer)) != -1) { 54 | outputStream.write(buffer, 0, bytesRead); 55 | } 56 | 57 | cursor.close(); 58 | outputStream.close(); 59 | inputStream.close(); 60 | 61 | return file; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendGrid.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import androidx.annotation.NonNull; 4 | 5 | import java.util.concurrent.Callable; 6 | 7 | public class SendGrid { 8 | 9 | private static final String MAIL_URL = "mail/send"; 10 | 11 | private String credentials; 12 | private SendGridCall api; 13 | 14 | private SendGrid(String apiKey) { 15 | this.credentials = createCredentials(apiKey); 16 | api = new SendGridCall(); 17 | } 18 | 19 | /** 20 | * Returns a SendGrid instance tied to your API key that is used 21 | * for initiating mail send requests. 22 | * 23 | * @param apiKey your SendGrid API key 24 | * @return the SendGrid instance tied to your API key 25 | */ 26 | public static SendGrid create(@NonNull String apiKey) { 27 | return new SendGrid(apiKey); 28 | } 29 | 30 | /** 31 | * API mail send request, provide with a {@link SendGridMail} and returns a Callable 32 | * {@link SendGridResponse}. 33 | * 34 | * The response will contain a successful {@link SendGridResponse#isSuccessful()} 35 | * state along with any associated error {@link SendGridResponse#getErrorMessage()} 36 | * in the event on an unsuccessful response. 37 | * 38 | * @param mail the SendGridMail to send to the API 39 | * @return the response generated from the API request 40 | */ 41 | public Callable send(@NonNull SendGridMail mail) { 42 | return api.call(MAIL_URL, credentials, SendGridMailBody.create(mail)); 43 | } 44 | 45 | private String createCredentials(String key) { 46 | return String.format("Bearer %s", key); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendGridCall.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import java.io.*; 4 | import java.net.HttpURLConnection; 5 | import java.net.URL; 6 | import java.util.concurrent.Callable; 7 | 8 | import static uk.co.jakebreen.sendgridandroid.SendGridResponse.Factory.error; 9 | import static uk.co.jakebreen.sendgridandroid.SendGridResponse.Factory.success; 10 | 11 | class SendGridCall { 12 | 13 | private static final String BASE_URL = "https://sendgrid.com/v3/"; 14 | 15 | Callable call(String url, final String key, final SendGridMailBody body) { 16 | final String apiUrl = String.format("%s%s", BASE_URL, url); 17 | return new Callable() { 18 | @Override 19 | public SendGridResponse call() throws Exception { 20 | final URL url1 = new URL(apiUrl); 21 | final HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection(); 22 | urlConnection.setDoOutput(true); 23 | urlConnection.setRequestMethod("POST"); 24 | urlConnection.setRequestProperty("Authorization", key); 25 | urlConnection.setRequestProperty("Accept", "application/json"); 26 | urlConnection.setRequestProperty("Content-Type", "application/json; utf-8"); 27 | 28 | OutputStream outputStream = urlConnection.getOutputStream(); 29 | outputStream.write(body.getBody().toString().getBytes("UTF-8")); 30 | outputStream.close(); 31 | 32 | InputStream inputStream; 33 | try { 34 | inputStream = urlConnection.getInputStream(); 35 | } catch (IOException exception) { 36 | inputStream = urlConnection.getErrorStream(); 37 | } 38 | 39 | int code = urlConnection.getResponseCode(); 40 | String response = SendGridCall.this.readInputStream(inputStream); 41 | urlConnection.disconnect(); 42 | 43 | return createResponse(code, response); 44 | } 45 | }; 46 | } 47 | 48 | private String readInputStream(final InputStream inputStream) throws IOException { 49 | final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 50 | final StringBuilder stringBuilder = new StringBuilder(); 51 | String line; 52 | while ((line = bufferedReader.readLine()) != null) { 53 | stringBuilder.append(line); 54 | } 55 | bufferedReader.close(); 56 | return stringBuilder.toString(); 57 | } 58 | 59 | private SendGridResponse createResponse(int code, String response) { 60 | if (code >= 200 && code < 300) 61 | return success(code); 62 | else 63 | return error(code, response); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendGridMail.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import androidx.annotation.NonNull; 6 | import androidx.annotation.Nullable; 7 | 8 | import org.json.JSONObject; 9 | 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | import static uk.co.jakebreen.sendgridandroid.FileEncoder.encodeFileToBase64; 18 | import static uk.co.jakebreen.sendgridandroid.FileEncoder.uriToFile; 19 | import static uk.co.jakebreen.sendgridandroid.SendGridMail.Attachment.isFile; 20 | 21 | public class SendGridMail { 22 | 23 | static final String EMPTY = ""; 24 | static final String TYPE_PLAIN = "text/plain"; 25 | static final String TYPE_HTML = "text/html"; 26 | 27 | static final String TRACKING_SETTING_CLICK_TRACKING = "click_tracking"; 28 | static final String TRACKING_SETTING_OPEN_TRACKING = "open_tracking"; 29 | static final String TRACKING_SETTING_SUBSCRIPTION_TRACKING = "subscription_tracking"; 30 | static final String TRACKING_SETTING_ENABLED = "enable"; 31 | 32 | private final Map to = new HashMap<>(); 33 | private final Map cc = new HashMap<>(); 34 | private final Map bcc = new HashMap<>(); 35 | private String subject; 36 | private final Map content = new HashMap<>(); 37 | private final Map from = new HashMap<>(); 38 | private final Map replyTo = new HashMap<>(); 39 | private final Map> trackingSettings = new HashMap<>(); 40 | private String templateId; 41 | private int sendAt; 42 | private List attachments = new ArrayList<>(); 43 | private JSONObject dynamicTemplateData; 44 | private int unsubscribeGroupId; 45 | private final List unsubscribeGroupIds = new ArrayList<>(); 46 | 47 | public SendGridMail() { } 48 | 49 | /** 50 | * Add a new recipient up to a maximum of 1000 recipients. 51 | * Email address must be specified and an optional name of person or company 52 | * that is receiving this mail. 53 | * 54 | * @param email the recipient's email address 55 | * @param name name of person or company that is receiving this mail 56 | */ 57 | public void addRecipient(@NonNull String email, @Nullable String name) { 58 | if (to.size() >= 1000) return; 59 | 60 | if (name == null) name = EMPTY; 61 | to.put(email, name); 62 | } 63 | 64 | /** 65 | * Add a new Carbon Copy recipient up to a maximum of 1000 recipients. 66 | * Email address must be specified and an optional name of person or company 67 | * that is receiving this mail. 68 | * 69 | * @param email the recipient's email address 70 | * @param name name of person or company that is receiving this mail 71 | */ 72 | public void addRecipientCarbonCopy(@NonNull String email, @Nullable String name) { 73 | if (cc.size() >= 1000) return; 74 | 75 | if (name == null) name = EMPTY; 76 | cc.put(email, name); 77 | } 78 | 79 | /** 80 | * Add a new Blind Carbon Copy recipient up to a maximum of 1000 recipients. 81 | * Email address must be specified and an optional name of person or company 82 | * that is receiving this mail. 83 | * 84 | * @param email the recipient's email address 85 | * @param name name of person or company that is receiving this mail 86 | */ 87 | public void addRecipientBlindCarbonCopy(@NonNull String email, @Nullable String name) { 88 | if (bcc.size() >= 1000) return; 89 | 90 | if (name == null) name = EMPTY; 91 | bcc.put(email, name); 92 | } 93 | 94 | /** 95 | * Provide the senders email address and optional name or company that is 96 | * sending this mail. 97 | * 98 | * @param email email of person or company that is sending this mail 99 | * @param name name of person or company that is sending this mail 100 | */ 101 | public void setFrom(@NonNull String email, @Nullable String name) { 102 | from.clear(); 103 | if (name == null) 104 | name = EMPTY; 105 | from.put(email, name); 106 | } 107 | 108 | /** 109 | * The name of the person or company that is sending the email. 110 | * 111 | * @param email email of person or company that is sending this mail 112 | * @param name name of person or company that is sending this mail 113 | */ 114 | public void setReplyTo(@NonNull String email, @Nullable String name) { 115 | replyTo.clear(); 116 | if (name == null) 117 | name = EMPTY; 118 | replyTo.put(email, name); 119 | } 120 | 121 | /** 122 | * The subject matter of your email. 123 | * 124 | * @param subject subject of your email 125 | */ 126 | public void setSubject(@NonNull String subject) { 127 | if (subject.length() == 0) 128 | subject = " "; 129 | this.subject = subject; 130 | } 131 | 132 | /** 133 | * The id of the template that this email should adhere to. 134 | * 135 | * @param templateId the id of your designated template 136 | */ 137 | public void setTemplateId(@NonNull String templateId) { 138 | this.templateId = templateId; 139 | } 140 | 141 | /** 142 | * Add a plain text body to your email using Content-Type: "text/plain". 143 | * 144 | * @param body the body of your email 145 | */ 146 | public void setContent(@NonNull String body) { 147 | if (body.length() == 0) 148 | body = " "; 149 | content.put(TYPE_PLAIN, body); 150 | } 151 | 152 | /** 153 | * Add a HTML body to your email using Content-Type: "text/html". 154 | * 155 | * @param body the body of your email 156 | */ 157 | public void setHtmlContent(@NonNull String body) { 158 | if (body.length() == 0) 159 | body = " "; 160 | content.put(TYPE_HTML, body); 161 | } 162 | 163 | /** 164 | * A unix timestamp allowing you to specify when you want your email to be delivered. 165 | * 166 | * @param sendAt the unix timestamp of when your email should be sent 167 | */ 168 | public void setSendAt(@NonNull int sendAt) { 169 | if (sendAt > System.currentTimeMillis() / 1000L) 170 | this.sendAt = sendAt; 171 | } 172 | 173 | /** 174 | * Add an attachment of type {@link File} to the email, up to a maximum of 10. 175 | * 176 | * @param file the content to be attached 177 | */ 178 | public void addAttachment(@NonNull File file) throws IOException { 179 | if (attachments.size() >= 10) 180 | return; 181 | if (isFile(file)) 182 | attachments.add(new Attachment(file)); 183 | } 184 | 185 | /** 186 | * Add an attachment of type {@link Uri} to the email, up to a maximum of 10. 187 | * 188 | * @param uri the content to be attached 189 | */ 190 | public void addAttachment(@NonNull Context context, @NonNull Uri uri) throws IOException { 191 | if (attachments.size() >= 10) 192 | return; 193 | final File file = uriToFile(context, uri); 194 | if (isFile(file)) 195 | attachments.add(new Attachment(file)); 196 | } 197 | 198 | /** 199 | * Allows you to track whether a recipient clicked a link in your email. 200 | * 201 | * @param enabled Indicates if this setting is enabled. 202 | */ 203 | public void setClickTrackingEnabled(@NonNull final Boolean enabled) { 204 | trackingSettings.put(TRACKING_SETTING_CLICK_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, enabled); }}); 205 | } 206 | 207 | /** 208 | * Allows you to track whether the email was opened or not, but including a single pixel image 209 | * in the body of the content. When the pixel is loaded, we can log that the email was opened. 210 | * 211 | * @param enabled Indicates if this setting is enabled. 212 | */ 213 | public void setOpenTrackingEnabled(@NonNull final Boolean enabled) { 214 | trackingSettings.put(TRACKING_SETTING_OPEN_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, enabled); }}); 215 | } 216 | 217 | /** 218 | * Allows you to insert a subscription management link at the bottom of the text and html 219 | * bodies of your email. If you would like to specify the location of the link within your 220 | * email, you may use the substitution_tag. 221 | * 222 | * @param enabled Indicates if this setting is enabled. 223 | */ 224 | public void setSubscriptionTrackingEnabled(@NonNull final Boolean enabled) { 225 | trackingSettings.put(TRACKING_SETTING_SUBSCRIPTION_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, enabled); }}); 226 | } 227 | 228 | /** 229 | * Dynamic template data is available using Handlebars syntax in Dynamic Transactional Templates. 230 | * 231 | * @param jsonObject of key/value pairs that the template expects 232 | */ 233 | public void setDynamicTemplateData(@NonNull JSONObject jsonObject) { 234 | dynamicTemplateData = jsonObject; 235 | } 236 | 237 | /** 238 | * Add an unsubscribe group id of type {@link Integer}. 239 | * 240 | * @param groupId the unsubscribe group to associate with this email 241 | */ 242 | public void setUnsubscribeGroupId(@NonNull int groupId) { 243 | unsubscribeGroupId = groupId; 244 | } 245 | 246 | /** 247 | * Add an unsubscribe group id of type {@link Integer} to the email or a list of unsubscribe 248 | * groups to display up to a maximum of 25. 249 | * 250 | * @param groupId the unsubscribe group to associate with this email 251 | * @param groupIds an array containing the unsubscribe groups that you would like to be 252 | * displayed on the unsubscribe preferences page 253 | */ 254 | public void setUnsubscribeGroupIds(@NonNull int groupId, List groupIds) { 255 | if (groupIds.size() > 25) 256 | throw new IllegalArgumentException("The list of unsubscribe group IDs is greater than 25."); 257 | 258 | unsubscribeGroupId = groupId; 259 | unsubscribeGroupIds.addAll(groupIds); 260 | } 261 | 262 | /** 263 | * Returns a list of attached file names. 264 | * 265 | * @return list of file names 266 | */ 267 | List getAttachments() { 268 | final List fileNames = new ArrayList<>(); 269 | for (Attachment a : attachments) { 270 | fileNames.add(a.filename); 271 | } 272 | return fileNames; 273 | } 274 | 275 | Map> getTrackingSettings() { 276 | return trackingSettings; 277 | } 278 | 279 | Map getRecipients() { 280 | return to; 281 | } 282 | 283 | Map getRecipientCarbonCopies() { 284 | return cc; 285 | } 286 | 287 | Map getRecipientBlindCarbonCopies() { 288 | return bcc; 289 | } 290 | 291 | String getSubject() { 292 | return subject; 293 | } 294 | 295 | Map getContent() { 296 | return content; 297 | } 298 | 299 | Map getFrom() { 300 | return from; 301 | } 302 | 303 | Map getReplyTo() { 304 | return replyTo; 305 | } 306 | 307 | String getTemplateId() { 308 | return templateId; 309 | } 310 | 311 | int getSendAt() { 312 | return sendAt; 313 | } 314 | 315 | List getFileAttachments() { 316 | return attachments; 317 | } 318 | 319 | JSONObject getDynamicTemplateData() { 320 | return dynamicTemplateData; 321 | } 322 | 323 | int getUnsubscribeGroupId() { 324 | return unsubscribeGroupId; 325 | } 326 | 327 | List getUnsubscribeGroupIds() { 328 | return unsubscribeGroupIds; 329 | } 330 | 331 | static class Attachment { 332 | private final String content; 333 | private final String filename; 334 | 335 | Attachment(File file) throws IOException { 336 | this.content = encodeFileToBase64(file); 337 | this.filename = file.getName(); 338 | } 339 | 340 | String getContent() { 341 | return content; 342 | } 343 | 344 | String getFilename() { 345 | return filename; 346 | } 347 | 348 | static boolean isFile(File file) { 349 | return (file != null && file.canRead() && file.exists() && file.isFile()); 350 | } 351 | } 352 | } 353 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendGridMailBody.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import org.json.JSONArray; 4 | import org.json.JSONException; 5 | import org.json.JSONObject; 6 | 7 | import java.util.Map; 8 | import java.util.Map.Entry; 9 | 10 | import uk.co.jakebreen.sendgridandroid.SendGridMail.Attachment; 11 | 12 | import static uk.co.jakebreen.sendgridandroid.SendGridMail.EMPTY; 13 | import static uk.co.jakebreen.sendgridandroid.SendGridMail.TYPE_HTML; 14 | import static uk.co.jakebreen.sendgridandroid.SendGridMail.TYPE_PLAIN; 15 | 16 | class SendGridMailBody { 17 | 18 | private static final String BODY_PERSONALISATIONS = "personalizations"; 19 | private static final String BODY_TO = "to"; 20 | private static final String BODY_CC = "cc"; 21 | private static final String BODY_BCC = "bcc"; 22 | private static final String BODY_FROM = "from"; 23 | private static final String BODY_SUBJECT = "subject"; 24 | private static final String BODY_CONTENT = "content"; 25 | private static final String BODY_TEMPLATE_ID = "template_id"; 26 | private static final String BODY_REPLY_TO = "reply_to"; 27 | private static final String BODY_SEND_AT = "send_at"; 28 | private static final String BODY_ATTACHMENTS = "attachments"; 29 | private static final String BODY_TRACKING_SETTINGS = "tracking_settings"; 30 | private static final String BODY_DYNAMIC_TEMPLATE_DATA = "dynamic_template_data"; 31 | private static final String BODY_UNSUBSCRIBE_GROUP = "asm"; 32 | 33 | private static final String PARAMS_EMAIL = "email"; 34 | private static final String PARAMS_NAME = "name"; 35 | private static final String PARAMS_CONTENT_TYPE = "type"; 36 | private static final String PARAMS_CONTENT_VALUE = "value"; 37 | private static final String PARAMS_ATTACHMENT_CONTENT = "content"; 38 | private static final String PARAMS_ATTACHMENT_FILENAME = "filename"; 39 | private static final String PARAM_UNSUBSCRIBE_GROUP_ID = "group_id"; 40 | private static final String PARAM_UNSUBSCRIBE_GROUP_IDS = "groups_to_display"; 41 | 42 | private final JSONObject body; 43 | 44 | private SendGridMailBody(JSONObject body) { 45 | this.body = body; 46 | } 47 | 48 | static SendGridMailBody create(SendGridMail mail) { 49 | return new SendGridMailBody(createMailBody(mail)); 50 | } 51 | 52 | private static JSONObject createMailBody(SendGridMail mail) { 53 | final JSONObject parent = new JSONObject(); 54 | try { 55 | final JSONArray personalization = new JSONArray(); 56 | final JSONObject personalizationObj = new JSONObject(); 57 | personalizationObj.put(BODY_TO, getEmailsArray(mail.getRecipients())); 58 | if (!mail.getRecipientCarbonCopies().isEmpty()) 59 | personalizationObj.put(BODY_CC, getEmailsArray(mail.getRecipientCarbonCopies())); 60 | if (!mail.getRecipientBlindCarbonCopies().isEmpty()) 61 | personalizationObj.put(BODY_BCC, getEmailsArray(mail.getRecipientBlindCarbonCopies())); 62 | if (mail.getDynamicTemplateData() != null) 63 | personalizationObj.put(BODY_DYNAMIC_TEMPLATE_DATA, mail.getDynamicTemplateData()); 64 | personalization.put(personalizationObj); 65 | 66 | parent.put(BODY_PERSONALISATIONS, personalization); 67 | parent.put(BODY_FROM, getFromParams(mail)); 68 | parent.put(BODY_SUBJECT, getSubjectParams(mail)); 69 | parent.put(BODY_CONTENT, getContentParams(mail)); 70 | if (mail.getTemplateId() != null) 71 | parent.put(BODY_TEMPLATE_ID, getTemplateId(mail)); 72 | if (!mail.getReplyTo().isEmpty()) 73 | parent.put(BODY_REPLY_TO, getReplyToParams(mail)); 74 | if (mail.getSendAt() != 0) 75 | parent.put(BODY_SEND_AT, getSendAt(mail)); 76 | if (mail.getAttachments().size() > 0) 77 | parent.put(BODY_ATTACHMENTS, getAttachments(mail)); 78 | if (mail.getTrackingSettings().size() > 0) { 79 | parent.put(BODY_TRACKING_SETTINGS, getTrackingSettings(mail)); 80 | } 81 | if (mail.getUnsubscribeGroupId() != 0) { 82 | parent.put(BODY_UNSUBSCRIBE_GROUP, getUnsubscribeGroup(mail)); 83 | } 84 | } catch (JSONException e) { 85 | e.printStackTrace(); 86 | } 87 | return parent; 88 | } 89 | 90 | JSONObject getBody() { 91 | return body; 92 | } 93 | 94 | static JSONArray getContentParams(SendGridMail mail) throws JSONException { 95 | final JSONArray jsonArray = new JSONArray(); 96 | final Map contentMap = mail.getContent(); 97 | 98 | // If using a template the content block must be at least a single character 99 | // https://github.com/Jakebreen/android-sendgrid/issues/10 100 | if (contentMap.isEmpty()) { 101 | final JSONObject jsonObjectPlain = new JSONObject(); 102 | jsonObjectPlain.put(PARAMS_CONTENT_TYPE, TYPE_PLAIN); 103 | jsonObjectPlain.put(PARAMS_CONTENT_VALUE, " "); 104 | jsonArray.put(jsonObjectPlain); 105 | final JSONObject jsonObjectHtml = new JSONObject(); 106 | jsonObjectHtml.put(PARAMS_CONTENT_TYPE, TYPE_HTML); 107 | jsonObjectHtml.put(PARAMS_CONTENT_VALUE, " "); 108 | jsonArray.put(jsonObjectHtml); 109 | return jsonArray; 110 | } 111 | 112 | if (contentMap.containsKey(TYPE_PLAIN)) { 113 | final JSONObject jsonObject = new JSONObject(); 114 | jsonObject.put(PARAMS_CONTENT_TYPE, TYPE_PLAIN); 115 | jsonObject.put(PARAMS_CONTENT_VALUE, contentMap.get(TYPE_PLAIN)); 116 | jsonArray.put(jsonObject); 117 | contentMap.remove(TYPE_PLAIN); 118 | } 119 | 120 | if (contentMap.containsKey(TYPE_HTML)) { 121 | final JSONObject jsonObject = new JSONObject(); 122 | jsonObject.put(PARAMS_CONTENT_TYPE, TYPE_HTML); 123 | jsonObject.put(PARAMS_CONTENT_VALUE, contentMap.get(TYPE_HTML)); 124 | jsonArray.put(jsonObject); 125 | contentMap.remove(TYPE_HTML); 126 | } 127 | 128 | for (Entry set : contentMap.entrySet()) { 129 | final JSONObject jsonObject = new JSONObject(); 130 | jsonObject.put(PARAMS_CONTENT_TYPE, set.getKey()); 131 | jsonObject.put(PARAMS_CONTENT_VALUE, set.getValue()); 132 | jsonArray.put(jsonObject); 133 | } 134 | return jsonArray; 135 | } 136 | 137 | static String getSubjectParams(SendGridMail mail) { 138 | return mail.getSubject(); 139 | } 140 | 141 | static String getTemplateId(SendGridMail mail) { 142 | return mail.getTemplateId(); 143 | } 144 | 145 | static JSONObject getFromParams(SendGridMail mail) throws JSONException { 146 | final JSONObject jsonObject = new JSONObject(); 147 | for (Entry set : mail.getFrom().entrySet()) { 148 | jsonObject.put(PARAMS_EMAIL, set.getKey()); 149 | jsonObject.put(PARAMS_NAME, set.getValue()); 150 | } 151 | return jsonObject; 152 | } 153 | 154 | static JSONObject getReplyToParams(SendGridMail mail) throws JSONException { 155 | final JSONObject jsonObject = new JSONObject(); 156 | for (Entry set : mail.getReplyTo().entrySet()) { 157 | jsonObject.put(PARAMS_EMAIL, set.getKey()); 158 | jsonObject.put(PARAMS_NAME, set.getValue()); 159 | } 160 | return jsonObject; 161 | } 162 | 163 | static int getSendAt(SendGridMail mail) { 164 | return mail.getSendAt(); 165 | } 166 | 167 | static JSONArray getAttachments(SendGridMail mail) throws JSONException { 168 | final JSONArray jsonArray = new JSONArray(); 169 | for (Attachment attachment : mail.getFileAttachments()) { 170 | if (attachment.getContent().isEmpty()) 171 | continue; 172 | JSONObject jsonObject = new JSONObject(); 173 | jsonObject.put(PARAMS_ATTACHMENT_CONTENT, attachment.getContent()); 174 | jsonObject.put(PARAMS_ATTACHMENT_FILENAME, attachment.getFilename()); 175 | jsonArray.put(jsonObject); 176 | } 177 | return jsonArray; 178 | } 179 | 180 | static JSONObject getTrackingSettings(SendGridMail mail) throws JSONException { 181 | final JSONObject jsonObject = new JSONObject(); 182 | for (Entry> set : mail.getTrackingSettings().entrySet()) { 183 | jsonObject.put(set.getKey(), set.getValue()); 184 | } 185 | return jsonObject; 186 | } 187 | 188 | static JSONObject getUnsubscribeGroup(SendGridMail mail) throws JSONException { 189 | final JSONObject jsonObject = new JSONObject(); 190 | jsonObject.put(PARAM_UNSUBSCRIBE_GROUP_ID, mail.getUnsubscribeGroupId()); 191 | 192 | if (!mail.getUnsubscribeGroupIds().isEmpty()) { 193 | final JSONArray jsonArray = new JSONArray(mail.getUnsubscribeGroupIds()); 194 | jsonObject.put(PARAM_UNSUBSCRIBE_GROUP_IDS, jsonArray); 195 | } 196 | 197 | return jsonObject; 198 | } 199 | 200 | static JSONArray getEmailsArray(Map emailMap) throws JSONException { 201 | int count = 0; 202 | final JSONArray jsonArray = new JSONArray(); 203 | for (Entry set : emailMap.entrySet()) { 204 | JSONObject jsonObject = new JSONObject(); 205 | jsonObject.put(PARAMS_EMAIL, set.getKey()); 206 | jsonObject.put(PARAMS_NAME, set.getValue().equals(EMPTY) ? null : set.getValue()); 207 | jsonArray.put(jsonObject); 208 | 209 | count ++; 210 | if (count >= 1000) break; 211 | } 212 | return jsonArray; 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendGridResponse.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import androidx.annotation.Nullable; 4 | 5 | public class SendGridResponse { 6 | 7 | private final int code; 8 | private final String errorMessage; 9 | private final Exception exception; 10 | 11 | private SendGridResponse(int code, @Nullable String errorMessage, @Nullable Exception exception) { 12 | this.code = code; 13 | this.errorMessage = errorMessage; 14 | this.exception = exception; 15 | } 16 | 17 | private static SendGridResponse create(int code, String errorMessage) { 18 | return new SendGridResponse(code, errorMessage, null); 19 | } 20 | 21 | private static SendGridResponse create(Exception exception) { 22 | return new SendGridResponse(0, "", exception); 23 | } 24 | 25 | /** 26 | * Return the boolean success state of the response. 27 | * 28 | * @return boolean success state 29 | */ 30 | public boolean isSuccessful() { 31 | return errorMessage == null; 32 | } 33 | 34 | /** 35 | * Returns the HTTP response code for the request. 36 | * 37 | * @return HTTP response code 38 | */ 39 | public int getCode() { 40 | return code; 41 | } 42 | 43 | /** 44 | * Returns the associated error message of a failed response. 45 | * NULL when successful. 46 | * 47 | * @return response error message 48 | */ 49 | public String getErrorMessage() { 50 | return errorMessage; 51 | } 52 | 53 | Exception getException() { 54 | return exception; 55 | } 56 | 57 | static class Factory { 58 | 59 | static SendGridResponse success(int response) { 60 | return SendGridResponse.create(response, null); 61 | } 62 | 63 | static SendGridResponse error(int response, String errorMessage) { 64 | return SendGridResponse.create(response, ErrorParser.parseError(errorMessage)); 65 | } 66 | 67 | static SendGridResponse error(Exception exception) { 68 | return SendGridResponse.create(exception); 69 | } 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendTask.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | public class SendTask { 4 | 5 | private final SendGrid sendGrid; 6 | 7 | public SendTask(SendGrid sendGrid) { 8 | this.sendGrid = sendGrid; 9 | } 10 | 11 | /** 12 | * API mail send request, provide with a {@link SendGridMail} and returns a {@link SendGridResponse}. 13 | * Rethrows any exceptions. 14 | * 15 | * @param mail the SendGridMail to send to the API 16 | * @return the response generated from the API request 17 | */ 18 | public SendGridResponse send(SendGridMail mail) throws Exception { 19 | final SendGridResponse response = new SendTaskAsync(sendGrid, mail).execute().get(); 20 | if (response.getException() != null) 21 | throw response.getException(); 22 | return response; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/java/uk/co/jakebreen/sendgridandroid/SendTaskAsync.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import android.os.AsyncTask; 4 | 5 | class SendTaskAsync extends AsyncTask { 6 | 7 | private final SendGrid sendGrid; 8 | private final SendGridMail mail; 9 | 10 | SendTaskAsync(SendGrid sendGrid, SendGridMail mail) { 11 | this.sendGrid = sendGrid; 12 | this.mail = mail; 13 | } 14 | 15 | @Override 16 | protected SendGridResponse doInBackground(Void... voids) { 17 | try { 18 | return sendGrid.send(mail).call(); 19 | } catch (Exception e) { 20 | return SendGridResponse.Factory.error(e); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/androidsendgrid/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Sendgrid Android 3 | 4 | -------------------------------------------------------------------------------- /androidsendgrid/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /androidsendgrid/src/test/java/uk/co/jakebreen/sendgridandroid/SendGridMailBodyTest.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.mockito.Mock; 8 | 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.util.*; 14 | 15 | import static org.junit.Assert.assertEquals; 16 | import static org.mockito.Mockito.mock; 17 | import static org.mockito.Mockito.when; 18 | import static org.mockito.MockitoAnnotations.initMocks; 19 | import static uk.co.jakebreen.sendgridandroid.SendGridMail.*; 20 | import static uk.co.jakebreen.sendgridandroid.SendGridMailBody.*; 21 | 22 | public class SendGridMailBodyTest { 23 | 24 | private static final String CONTENT_BODY = "Email content body"; 25 | 26 | @Mock SendGridMail mail; 27 | 28 | @Before 29 | public void setup() { 30 | initMocks(this); 31 | } 32 | 33 | @Test 34 | public void givenListOfToEmails_whenCreatingMailBody_thenReturnJsonBody() throws JSONException, IOException { 35 | final Map map = new HashMap<>(); 36 | map.put("john.doe@example.com", "John Doe"); 37 | map.put("kate.green@example.com", "Kate Green"); 38 | map.put("will.smith@example.com", "Will Smith"); 39 | when(mail.getRecipients()).thenReturn(map); 40 | 41 | assertEquals(parseJsonFile("/json/emails_array"), getEmailsArray(mail.getRecipients()).toString()); 42 | } 43 | 44 | @Test 45 | public void givenListOfCcEmails_whenCreatingMailBody_thenReturnJsonBody() throws JSONException, IOException { 46 | final Map map = new HashMap<>(); 47 | map.put("john.doe@example.com", "John Doe"); 48 | map.put("kate.green@example.com", "Kate Green"); 49 | map.put("will.smith@example.com", "Will Smith"); 50 | when(mail.getRecipientCarbonCopies()).thenReturn(map); 51 | 52 | assertEquals(parseJsonFile("/json/emails_array"), getEmailsArray(mail.getRecipientCarbonCopies()).toString()); 53 | } 54 | 55 | @Test 56 | public void givenListOfBccEmails_whenCreatingMailBody_thenReturnJsonBody() throws JSONException, IOException { 57 | final Map map = new HashMap<>(); 58 | map.put("john.doe@example.com", "John Doe"); 59 | map.put("kate.green@example.com", "Kate Green"); 60 | map.put("will.smith@example.com", "Will Smith"); 61 | when(mail.getRecipientBlindCarbonCopies()).thenReturn(map); 62 | 63 | assertEquals(parseJsonFile("/json/emails_array"), getEmailsArray(mail.getRecipientBlindCarbonCopies()).toString()); 64 | } 65 | 66 | @Test 67 | public void givenToEmail_whenCreatingMailBodyAndNameIsEmpty_thenReturnJsonBodyWithoutNameValue() throws JSONException { 68 | final String expectedValue = "[{\"email\":\"john.doe@example.com\"}]"; 69 | 70 | final Map map = new HashMap<>(); 71 | map.put("john.doe@example.com", EMPTY); 72 | when(mail.getRecipients()).thenReturn(map); 73 | 74 | assertEquals(expectedValue, getEmailsArray(mail.getRecipients()).toString()); 75 | } 76 | 77 | @Test 78 | public void givenFromEmail_whenCreatingMailBody_thenReturnJsonBody() throws JSONException { 79 | final String expectedValue = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"}"; 80 | 81 | final Map map = new HashMap<>(); 82 | map.put("john.doe@example.com", "John Doe"); 83 | when(mail.getFrom()).thenReturn(map); 84 | 85 | assertEquals(expectedValue, getFromParams(mail).toString()); 86 | } 87 | 88 | @Test 89 | public void givenPlainContent_whenCreatingMailBody_thenPlainContentAdded_andNoHtmlContent() throws JSONException { 90 | final String expectedValue = "[{\"type\":\"text/plain\",\"value\":\"" + CONTENT_BODY + "\"}]"; 91 | 92 | final Map map = new HashMap<>(); 93 | map.put(TYPE_PLAIN, CONTENT_BODY); 94 | when(mail.getContent()).thenReturn(map); 95 | 96 | assertEquals(expectedValue, getContentParams(mail).toString()); 97 | } 98 | 99 | @Test 100 | public void givenHtmlContent_whenCreatingMailBody_thenHtmlContentAdded_andNoPlainContent() throws JSONException { 101 | final String expectedValue = "[{\"type\":\"text/html\",\"value\":\"" + CONTENT_BODY + "\"}]"; 102 | 103 | final Map map = new HashMap<>(); 104 | map.put(TYPE_HTML, CONTENT_BODY); 105 | when(mail.getContent()).thenReturn(map); 106 | 107 | assertEquals(expectedValue, getContentParams(mail).toString()); 108 | } 109 | 110 | @Test 111 | public void givenContentsWithPlainTypeThenHtmlType_whenCreatingMailBody_thenReturnJsonBodyInThatOrder() throws JSONException { 112 | final String expectedValue = "[{\"type\":\"text/plain\",\"value\":\"" + CONTENT_BODY + "\"}," + "{\"type\":\"text/html\",\"value\":\"" + CONTENT_BODY + "\"}]"; 113 | 114 | final Map map = new HashMap<>(); 115 | map.put(TYPE_PLAIN, CONTENT_BODY); 116 | map.put(TYPE_HTML, CONTENT_BODY); 117 | when(mail.getContent()).thenReturn(map); 118 | 119 | assertEquals(expectedValue, getContentParams(mail).toString()); 120 | } 121 | 122 | @Test 123 | public void givenContentsWithHtmlTypeThenPlainType_whenCreatingMailBody_thenReturnJsonBodyInCorrectOrder() throws JSONException { 124 | final String expectedValue = "[{\"type\":\"text/plain\",\"value\":\"" + CONTENT_BODY + "\"}," + "{\"type\":\"text/html\",\"value\":\"" + CONTENT_BODY + "\"}]"; 125 | 126 | final Map map = new HashMap<>(); 127 | map.put(TYPE_HTML, CONTENT_BODY); 128 | map.put(TYPE_PLAIN, CONTENT_BODY); 129 | when(mail.getContent()).thenReturn(map); 130 | 131 | assertEquals(expectedValue, getContentParams(mail).toString()); 132 | } 133 | 134 | @Test 135 | public void givenAttachment_whenCreatingMailBody_thenReturnJsonBody() throws JSONException { 136 | final String expectedValue = "[{\"filename\":\"TestFile.txt\",\"content\":\"dgFAtXCDASfghjgj4\"}]"; 137 | 138 | final SendGridMail.Attachment attachment = mock(SendGridMail.Attachment.class); 139 | when(attachment.getContent()).thenReturn("dgFAtXCDASfghjgj4"); 140 | when(attachment.getFilename()).thenReturn("TestFile.txt"); 141 | 142 | final List map = new ArrayList<>(); 143 | map.add(attachment); 144 | 145 | when(mail.getFileAttachments()).thenReturn(map); 146 | 147 | assertEquals(expectedValue, getAttachments(mail).toString()); 148 | } 149 | 150 | @Test 151 | public void givenMultipleMailParameters_whenCreatingMailBody_thenReturnJsonBody() throws IOException { 152 | final Map toMap = new HashMap<>(); 153 | toMap.put("john.doe@example.com", "John Doe"); 154 | toMap.put("kate.green@example.com", "Kate Green"); 155 | toMap.put("will.smith@example.com", "Will Smith"); 156 | when(mail.getRecipients()).thenReturn(toMap); 157 | 158 | final Map ccMap = new HashMap<>(); 159 | ccMap.put("john.doe@example.com", "John Doe"); 160 | ccMap.put("kate.green@example.com", "Kate Green"); 161 | ccMap.put("will.smith@example.com", "Will Smith"); 162 | when(mail.getRecipientCarbonCopies()).thenReturn(ccMap); 163 | 164 | final Map bccMap = new HashMap<>(); 165 | bccMap.put("john.doe@example.com", "John Doe"); 166 | bccMap.put("kate.green@example.com", "Kate Green"); 167 | bccMap.put("will.smith@example.com", "Will Smith"); 168 | when(mail.getRecipientBlindCarbonCopies()).thenReturn(bccMap); 169 | 170 | final Map fromMap = new HashMap<>(); 171 | fromMap.put("john.doe@example.com", "John Doe"); 172 | when(mail.getFrom()).thenReturn(fromMap); 173 | 174 | when(mail.getSubject()).thenReturn("Mail subject"); 175 | 176 | final Map contentMap = new HashMap<>(); 177 | contentMap.put(TYPE_PLAIN, CONTENT_BODY); 178 | contentMap.put(TYPE_HTML, CONTENT_BODY); 179 | when(mail.getContent()).thenReturn(contentMap); 180 | 181 | when(mail.getTemplateId()).thenReturn("733ba07f-ead1-41fc-933a-3976baa23716"); 182 | 183 | final Map replyMap = new HashMap<>(); 184 | replyMap.put("no-reply@email.com", "No reply"); 185 | when(mail.getReplyTo()).thenReturn(replyMap); 186 | 187 | assertEquals(parseJsonFile("/json/email"), create(mail).getBody().toString()); 188 | } 189 | 190 | @Test 191 | public void givenAllTrackingSettingsEnabled_whenCreatingMailBody_thenReturnJsonBody() throws IOException { 192 | final Map map = new HashMap<>(); 193 | map.put("john.doe@example.com", "John Doe"); 194 | map.put("kate.green@example.com", "Kate Green"); 195 | map.put("will.smith@example.com", "Will Smith"); 196 | when(mail.getRecipients()).thenReturn(map); 197 | 198 | final Map> trackingSettings = new HashMap<>(); 199 | trackingSettings.put(TRACKING_SETTING_CLICK_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, true); }}); 200 | trackingSettings.put(TRACKING_SETTING_OPEN_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, true); }}); 201 | trackingSettings.put(TRACKING_SETTING_SUBSCRIPTION_TRACKING, new HashMap() {{ put(TRACKING_SETTING_ENABLED, true); }}); 202 | when(mail.getTrackingSettings()).thenReturn(trackingSettings); 203 | 204 | assertEquals(parseJsonFile("/json/emails_tracking_settings_enabled"), create(mail).getBody().toString()); 205 | } 206 | 207 | @Test 208 | public void givenDynamicTemplateVariables_whenCreatingMailBody_thenReturnJsonBody() throws IOException, JSONException { 209 | final Map toMap = new HashMap<>(); 210 | toMap.put("example@sendgrid.net", EMPTY); 211 | when(mail.getRecipients()).thenReturn(toMap); 212 | 213 | when(mail.getTemplateId()).thenReturn("733ba07f-ead1-41fc-933a-3976baa23716"); 214 | 215 | final JSONObject dynamicTemplateData = new JSONObject(); 216 | dynamicTemplateData.put("forename", "Englebert"); 217 | dynamicTemplateData.put("surname", "Humperdink"); 218 | dynamicTemplateData.put("age", 85); 219 | dynamicTemplateData.put("retired", true); 220 | when(mail.getDynamicTemplateData()).thenReturn(dynamicTemplateData); 221 | 222 | final Map contentMap = new HashMap<>(); 223 | contentMap.put(TYPE_PLAIN, CONTENT_BODY); 224 | contentMap.put(TYPE_HTML, CONTENT_BODY); 225 | when(mail.getContent()).thenReturn(contentMap); 226 | 227 | final Map fromMap = new HashMap<>(); 228 | fromMap.put("john.doe@example.com", "John Doe"); 229 | when(mail.getFrom()).thenReturn(fromMap); 230 | 231 | assertEquals(parseJsonFile("/json/email_dynamic_template"), create(mail).getBody().toString()); 232 | } 233 | 234 | @Test 235 | public void givenDynamicTemplate_whenContentNotIncluded_thenReturnJsonBodyWithEmptyContentBlock() throws IOException { 236 | final Map toMap = new HashMap<>(); 237 | toMap.put("example@sendgrid.net", EMPTY); 238 | when(mail.getRecipients()).thenReturn(toMap); 239 | 240 | final Map fromMap = new HashMap<>(); 241 | fromMap.put("john.doe@example.com", "John Doe"); 242 | when(mail.getFrom()).thenReturn(fromMap); 243 | 244 | assertEquals(parseJsonFile("/json/email_content_empty"), create(mail).getBody().toString()); 245 | } 246 | 247 | @Test 248 | public void givenPlainContent_thenNoHtmlContent() throws IOException { 249 | final Map toMap = new HashMap<>(); 250 | toMap.put("example@sendgrid.net", EMPTY); 251 | when(mail.getRecipients()).thenReturn(toMap); 252 | 253 | final Map fromMap = new HashMap<>(); 254 | fromMap.put("john.doe@example.com", "John Doe"); 255 | when(mail.getFrom()).thenReturn(fromMap); 256 | 257 | final Map contentMap = new HashMap<>(); 258 | contentMap.put(TYPE_PLAIN, CONTENT_BODY); 259 | when(mail.getContent()).thenReturn(contentMap); 260 | 261 | assertEquals(parseJsonFile("/json/email_content_html_empty"), create(mail).getBody().toString()); 262 | } 263 | 264 | @Test 265 | public void givenHtmlContent_thenNoPlainContent() throws IOException { 266 | final Map toMap = new HashMap<>(); 267 | toMap.put("example@sendgrid.net", EMPTY); 268 | when(mail.getRecipients()).thenReturn(toMap); 269 | 270 | final Map fromMap = new HashMap<>(); 271 | fromMap.put("john.doe@example.com", "John Doe"); 272 | when(mail.getFrom()).thenReturn(fromMap); 273 | 274 | final Map contentMap = new HashMap<>(); 275 | contentMap.put(TYPE_HTML, CONTENT_BODY); 276 | when(mail.getContent()).thenReturn(contentMap); 277 | 278 | assertEquals(parseJsonFile("/json/email_content_plain_empty"), create(mail).getBody().toString()); 279 | } 280 | 281 | @Test 282 | public void givenUnsubscribeGroupIds_thenReturnJsonBody() throws IOException { 283 | final Map toMap = new HashMap<>(); 284 | toMap.put("example@sendgrid.net", EMPTY); 285 | when(mail.getRecipients()).thenReturn(toMap); 286 | 287 | final Map fromMap = new HashMap<>(); 288 | fromMap.put("john.doe@example.com", "John Doe"); 289 | when(mail.getFrom()).thenReturn(fromMap); 290 | 291 | final Map contentMap = new HashMap<>(); 292 | contentMap.put(TYPE_HTML, CONTENT_BODY); 293 | when(mail.getContent()).thenReturn(contentMap); 294 | 295 | when(mail.getUnsubscribeGroupId()).thenReturn(1000); 296 | when(mail.getUnsubscribeGroupIds()).thenReturn(Arrays.asList(1000, 2000, 3000)); 297 | 298 | assertEquals(parseJsonFile("/json/email_unsubscribe_groups"), create(mail).getBody().toString()); 299 | } 300 | 301 | private String parseJsonFile(String file) throws IOException { 302 | final InputStream inputStream = getClass().getResourceAsStream(file); 303 | final StringBuilder stringBuilder = new StringBuilder(); 304 | final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 305 | String read; 306 | 307 | while ((read = bufferedReader.readLine()) != null) 308 | stringBuilder.append(read.trim()); 309 | 310 | bufferedReader.close(); 311 | return stringBuilder.toString(); 312 | } 313 | 314 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/java/uk/co/jakebreen/sendgridandroid/SendGridTest.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import org.mockito.Mock; 6 | 7 | import java.util.concurrent.Callable; 8 | 9 | import static junit.framework.TestCase.assertTrue; 10 | import static org.junit.Assert.assertEquals; 11 | import static org.junit.Assert.assertFalse; 12 | import static org.mockito.ArgumentMatchers.any; 13 | import static org.mockito.ArgumentMatchers.anyString; 14 | import static org.mockito.Mockito.when; 15 | import static org.mockito.MockitoAnnotations.initMocks; 16 | import static uk.co.jakebreen.sendgridandroid.ErrorParser.parseError; 17 | 18 | public class SendGridTest { 19 | 20 | private static final int RESPONSE_202 = 202; 21 | private static final int RESPONSE_401 = 401; 22 | private static final String API_KEY = "api_key"; 23 | 24 | @Mock SendGridMail mail; 25 | @Mock SendGridCall api; 26 | @Mock Callable callable; 27 | @Mock SendGridResponse response; 28 | 29 | private SendGrid sendGrid; 30 | 31 | @Before 32 | public void setup() { 33 | initMocks(this); 34 | sendGrid = SendGrid.create(API_KEY); 35 | } 36 | 37 | @Test 38 | public void givenSendMailRequest_whenRequestIsSuccessful_thenReturnSuccessfulResponse() throws Exception { 39 | when(response.getCode()).thenReturn(RESPONSE_202); 40 | when(response.isSuccessful()).thenReturn(true); 41 | when(callable.call()).thenReturn(response); 42 | when(api.call(anyString(), anyString(), any(SendGridMailBody.class))).thenReturn(callable); 43 | 44 | sendGrid.send(mail); 45 | 46 | assertEquals(callable.call().getCode(), RESPONSE_202); 47 | assertTrue(callable.call().isSuccessful()); 48 | } 49 | 50 | @Test 51 | public void givenSendMailRequest_whenRequestIsUnsuccessfulWithError_thenReturnUnsuccessfulResponse() throws Exception { 52 | String exampleResponse = "{\"errors\":[{\"message\":\"Does not contain a valid address.\"," + 53 | "\"field\":\"personalizations.0.to.0.email\"," + 54 | "\"help\":\"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.to\"}]}"; 55 | 56 | when(response.getCode()).thenReturn(RESPONSE_401); 57 | when(response.isSuccessful()).thenReturn(false); 58 | when(response.getErrorMessage()).thenReturn("Does not contain a valid address."); 59 | when(callable.call()).thenReturn(response); 60 | when(api.call(anyString(), anyString(), any(SendGridMailBody.class))).thenReturn(callable); 61 | 62 | sendGrid.send(mail); 63 | 64 | assertEquals(callable.call().getCode(), RESPONSE_401); 65 | assertFalse(callable.call().isSuccessful()); 66 | assertEquals(callable.call().getErrorMessage(), parseError(exampleResponse)); 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "cc":[ 5 | { 6 | "name":"John Doe", 7 | "email":"john.doe@example.com" 8 | }, 9 | { 10 | "name":"Will Smith", 11 | "email":"will.smith@example.com" 12 | }, 13 | { 14 | "name":"Kate Green", 15 | "email":"kate.green@example.com" 16 | } 17 | ], 18 | "bcc":[ 19 | { 20 | "name":"John Doe", 21 | "email":"john.doe@example.com" 22 | }, 23 | { 24 | "name":"Will Smith", 25 | "email":"will.smith@example.com" 26 | }, 27 | { 28 | "name":"Kate Green", 29 | "email":"kate.green@example.com" 30 | } 31 | ], 32 | "to":[ 33 | { 34 | "name":"John Doe", 35 | "email":"john.doe@example.com" 36 | }, 37 | { 38 | "name":"Will Smith", 39 | "email":"will.smith@example.com" 40 | }, 41 | { 42 | "name":"Kate Green", 43 | "email":"kate.green@example.com" 44 | } 45 | ] 46 | } 47 | ], 48 | "reply_to":{ 49 | "name":"No reply", 50 | "email":"no-reply@email.com" 51 | }, 52 | "subject":"Mail subject", 53 | "from":{ 54 | "name":"John Doe", 55 | "email":"john.doe@example.com" 56 | }, 57 | "template_id":"733ba07f-ead1-41fc-933a-3976baa23716", 58 | "content":[ 59 | { 60 | "type":"text/plain", 61 | "value":"Email content body" 62 | }, 63 | { 64 | "type":"text/html", 65 | "value":"Email content body" 66 | } 67 | ] 68 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email_content_empty: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "to":[ 5 | { 6 | "email":"example@sendgrid.net" 7 | } 8 | ] 9 | } 10 | ], 11 | "from":{ 12 | "name":"John Doe", 13 | "email":"john.doe@example.com" 14 | }, 15 | "content":[ 16 | { 17 | "type":"text/plain", 18 | "value":" " 19 | }, 20 | { 21 | "type":"text/html", 22 | "value":" " 23 | } 24 | ] 25 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email_content_html_empty: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "to":[ 5 | { 6 | "email":"example@sendgrid.net" 7 | } 8 | ] 9 | } 10 | ], 11 | "from":{ 12 | "name":"John Doe", 13 | "email":"john.doe@example.com" 14 | }, 15 | "content":[ 16 | { 17 | "type":"text/plain", 18 | "value":"Email content body" 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email_content_plain_empty: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "to":[ 5 | { 6 | "email":"example@sendgrid.net" 7 | } 8 | ] 9 | } 10 | ], 11 | "from":{ 12 | "name":"John Doe", 13 | "email":"john.doe@example.com" 14 | }, 15 | "content":[ 16 | { 17 | "type":"text/html", 18 | "value":"Email content body" 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email_dynamic_template: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "dynamic_template_data":{ 5 | "forename":"Englebert", 6 | "surname":"Humperdink", 7 | "retired":true, 8 | "age":85 9 | }, 10 | "to":[ 11 | { 12 | "email":"example@sendgrid.net" 13 | } 14 | ] 15 | } 16 | ], 17 | "from":{ 18 | "name":"John Doe", 19 | "email":"john.doe@example.com" 20 | }, 21 | "template_id":"733ba07f-ead1-41fc-933a-3976baa23716", 22 | "content":[ 23 | { 24 | "type":"text/plain", 25 | "value":"Email content body" 26 | }, 27 | { 28 | "type":"text/html", 29 | "value":"Email content body" 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/email_unsubscribe_groups: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "to":[ 5 | { 6 | "email":"example@sendgrid.net" 7 | } 8 | ] 9 | } 10 | ], 11 | "from":{ 12 | "name":"John Doe", 13 | "email":"john.doe@example.com" 14 | }, 15 | "asm": 16 | { 17 | "group_id":1000, 18 | "groups_to_display":[1000,2000,3000] 19 | }, 20 | "content":[ 21 | { 22 | "type":"text/html", 23 | "value":"Email content body" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/emails_array: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name":"John Doe", 4 | "email":"john.doe@example.com" 5 | }, 6 | { 7 | "name":"Will Smith", 8 | "email":"will.smith@example.com" 9 | }, 10 | { 11 | "name":"Kate Green", 12 | "email":"kate.green@example.com" 13 | } 14 | ] -------------------------------------------------------------------------------- /androidsendgrid/src/test/res/json/emails_tracking_settings_enabled: -------------------------------------------------------------------------------- 1 | { 2 | "personalizations":[ 3 | { 4 | "to":[ 5 | { 6 | "name":"John Doe", 7 | "email":"john.doe@example.com" 8 | }, 9 | { 10 | "name":"Will Smith", 11 | "email":"will.smith@example.com" 12 | }, 13 | { 14 | "name":"Kate Green", 15 | "email":"kate.green@example.com" 16 | } 17 | ] 18 | } 19 | ], 20 | "tracking_settings":{ 21 | "click_tracking":{ 22 | "enable":true 23 | }, 24 | "subscription_tracking":{ 25 | "enable":true 26 | }, 27 | "open_tracking":{ 28 | "enable":true 29 | } 30 | }, 31 | "from":{}, 32 | "content":[ 33 | { 34 | "type":"text/plain", 35 | "value":" " 36 | }, 37 | { 38 | "type":"text/html", 39 | "value":" " 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | jcenter() 5 | 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:7.2.1' 9 | } 10 | } 11 | 12 | allprojects { 13 | repositories { 14 | google() 15 | jcenter() 16 | 17 | } 18 | } 19 | 20 | task clean(type: Delete) { 21 | delete rootProject.buildDir 22 | } 23 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1024m 10 | android.useAndroidX=true 11 | android.enableJetifier=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jul 19 09:08:58 BST 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /images/heading-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jakebreen/android-sendgrid/93514610fa957008a238a1967ad5213645ac8f32/images/heading-image.jpg -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':androidsendgrid', ':testapp' 2 | -------------------------------------------------------------------------------- /testapp/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /testapp/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 32 5 | 6 | defaultConfig { 7 | applicationId "uk.co.jakebreen.sendgridandroid.testapp" 8 | minSdkVersion 24 9 | targetSdkVersion 32 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 14 | } 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | 23 | } 24 | 25 | dependencies { 26 | implementation fileTree(dir: 'libs', include: ['*.jar']) 27 | implementation project(':androidsendgrid') 28 | 29 | implementation 'androidx.appcompat:appcompat:1.4.2' 30 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 31 | 32 | implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' 33 | implementation 'io.reactivex.rxjava2:rxjava:2.2.21' 34 | } 35 | -------------------------------------------------------------------------------- /testapp/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /testapp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /testapp/src/main/java/uk/co/jakebreen/sendgridandroid/testapp/FileUtil.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid.testapp; 2 | 3 | import android.content.Context; 4 | import android.database.Cursor; 5 | import android.net.Uri; 6 | import android.provider.OpenableColumns; 7 | 8 | import java.io.File; 9 | import java.io.FileNotFoundException; 10 | import java.io.FileOutputStream; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | 14 | class FileUtil { 15 | 16 | private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; 17 | 18 | private FileUtil() { } 19 | 20 | static File from(Context context, Uri uri) throws IOException { 21 | InputStream inputStream = context.getContentResolver().openInputStream(uri); 22 | String fileName = getFileName(context, uri); 23 | String[] splitName = splitFileName(fileName); 24 | File tempFile = File.createTempFile(splitName[0], splitName[1]); 25 | tempFile.deleteOnExit(); 26 | FileOutputStream out = null; 27 | try { 28 | out = new FileOutputStream(tempFile); 29 | } catch (FileNotFoundException e) { 30 | e.printStackTrace(); 31 | } 32 | 33 | 34 | if (inputStream != null) { 35 | int bytesRead; 36 | byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 37 | while ((bytesRead = inputStream.read(buffer)) != -1) { 38 | out.write(buffer, 0, bytesRead); 39 | } 40 | inputStream.close(); 41 | } 42 | 43 | if (out != null) { 44 | out.close(); 45 | } 46 | return tempFile; 47 | } 48 | 49 | private static String[] splitFileName(String fileName) { 50 | String name = fileName; 51 | String extension = ""; 52 | int i = fileName.lastIndexOf("."); 53 | if (i != -1) { 54 | name = fileName.substring(0, i); 55 | extension = fileName.substring(i); 56 | } 57 | 58 | return new String[]{name, extension}; 59 | } 60 | 61 | private static String getFileName(Context context, Uri uri) { 62 | String result = null; 63 | if (uri.getScheme().equals("content")) { 64 | try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) { 65 | if (cursor != null && cursor.moveToFirst()) { 66 | result = cursor.getString(cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)); 67 | } 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | } 72 | if (result == null) { 73 | result = uri.getPath(); 74 | int cut = result.lastIndexOf(File.separator); 75 | if (cut != -1) { 76 | result = result.substring(cut + 1); 77 | } 78 | } 79 | return result; 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /testapp/src/main/java/uk/co/jakebreen/sendgridandroid/testapp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package uk.co.jakebreen.sendgridandroid.testapp; 2 | 3 | import android.content.Intent; 4 | import android.content.SharedPreferences; 5 | import android.net.Uri; 6 | import android.os.Bundle; 7 | import android.view.View; 8 | import android.widget.Button; 9 | import android.widget.EditText; 10 | import android.widget.TextView; 11 | import android.widget.Toast; 12 | 13 | import androidx.appcompat.app.AppCompatActivity; 14 | 15 | import org.json.JSONException; 16 | import org.json.JSONObject; 17 | 18 | import java.io.File; 19 | import java.io.IOException; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | import java.util.concurrent.ExecutionException; 23 | 24 | import io.reactivex.disposables.Disposable; 25 | import uk.co.jakebreen.sendgridandroid.SendGrid; 26 | import uk.co.jakebreen.sendgridandroid.SendGridMail; 27 | import uk.co.jakebreen.sendgridandroid.SendGridResponse; 28 | import uk.co.jakebreen.sendgridandroid.SendTask; 29 | import uk.co.jakebreen.testapp.R; 30 | 31 | public class MainActivity extends AppCompatActivity { 32 | 33 | private static final String PREFERENCES = "sendgrid_preferences"; 34 | private static final String PREFERENCE_RECIPIENT_EMAIL = "PREFERENCE_RECIPIENT_EMAIL"; 35 | private static final String PREFERENCE_RECIPIENT_NAME = "PREFERENCE_RECIPIENT_NAME"; 36 | private static final String PREFERENCE_SENDER_EMAIL = "PREFERENCE_SENDER_EMAIL"; 37 | private static final String PREFERENCE_SENDER_NAME = "PREFERENCE_SENDER_NAME"; 38 | private static final String PREFERENCE_SUBJECT = "PREFERENCE_SUBJECT"; 39 | private static final String PREFERENCE_CONTENT = "PREFERENCE_CONTENT"; 40 | 41 | // Include template ID if required and use 'mail.setDynamicTemplateData()' to include customizations 42 | private static final String TEMPLATE_ID = ""; 43 | 44 | private static final int REQUEST_CODE = 1; 45 | 46 | private Button btnSend, btnAddAttachment, btnClearAttachments; 47 | private EditText etRecipientEmail, etRecipientName; 48 | private EditText etSenderEmail, etSenderName; 49 | private EditText etSubject, etContent; 50 | private EditText etReplyToEmail, getEtReplyToName; 51 | private TextView tvAttachments; 52 | 53 | private SendGrid sendGrid; 54 | private final List attachments = new ArrayList<>(); 55 | private final List uris = new ArrayList<>(); 56 | private Disposable disposable; 57 | private SharedPreferences sharedPreferences; 58 | 59 | @Override 60 | protected void onCreate(Bundle savedInstanceState) { 61 | super.onCreate(savedInstanceState); 62 | setContentView(R.layout.activity_main); 63 | 64 | sharedPreferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE); 65 | 66 | // Add API KEY 67 | sendGrid = SendGrid.create(""); 68 | 69 | btnSend = findViewById(R.id.btn_send); 70 | btnAddAttachment = findViewById(R.id.btn_attachment); 71 | etRecipientEmail = findViewById(R.id.et_recipient_email); 72 | etRecipientName = findViewById(R.id.et_recipient_name); 73 | etSenderEmail = findViewById(R.id.et_senders_email); 74 | etSenderName = findViewById(R.id.et_senders_name); 75 | etSubject = findViewById(R.id.et_subject); 76 | etContent = findViewById(R.id.et_content); 77 | etReplyToEmail = findViewById(R.id.et_reply_to_email); 78 | getEtReplyToName = findViewById(R.id.et_reply_to_name); 79 | tvAttachments = findViewById(R.id.tv_attachments); 80 | btnClearAttachments = findViewById(R.id.btn_clear_attachments); 81 | 82 | btnSend.setOnClickListener(new View.OnClickListener() { 83 | @Override 84 | public void onClick(View v) { 85 | MainActivity.this.sendMail(); 86 | } 87 | }); 88 | btnAddAttachment.setOnClickListener(new View.OnClickListener() { 89 | @Override 90 | public void onClick(View v) { 91 | MainActivity.this.addAttachment(); 92 | } 93 | }); 94 | btnClearAttachments.setOnClickListener(new View.OnClickListener() { 95 | @Override 96 | public void onClick(View v) { 97 | MainActivity.this.clearAttachments(); 98 | } 99 | }); 100 | 101 | etRecipientEmail.setText(sharedPreferences.getString(PREFERENCE_RECIPIENT_EMAIL, "")); 102 | etRecipientName.setText(sharedPreferences.getString(PREFERENCE_RECIPIENT_NAME, "")); 103 | etSenderEmail.setText(sharedPreferences.getString(PREFERENCE_SENDER_EMAIL, "")); 104 | etSenderName.setText(sharedPreferences.getString(PREFERENCE_SENDER_NAME, "")); 105 | etSubject.setText(sharedPreferences.getString(PREFERENCE_SUBJECT, "")); 106 | etContent.setText(sharedPreferences.getString(PREFERENCE_CONTENT, "")); 107 | 108 | etSenderEmail.setText("android-sendgrid@testapp.com"); 109 | etSenderName.setText("Test App"); 110 | etRecipientName.setText("Recipient"); 111 | etSubject.setText("Test App Subject"); 112 | 113 | clearAttachments(); 114 | } 115 | 116 | private void clearAttachments() { 117 | attachments.clear(); 118 | uris.clear(); 119 | setAttachmentCount(); 120 | } 121 | 122 | private void setAttachmentCount() { 123 | final int count = attachments.size() + uris.size(); 124 | tvAttachments.setText(String.format("%s Attachments", count)); 125 | if (count >= 10) 126 | btnAddAttachment.setEnabled(false); 127 | else 128 | btnAddAttachment.setEnabled(true); 129 | } 130 | 131 | private void sendMail() { 132 | final String recipientEmail = etRecipientEmail.getText().toString(); 133 | final String recipientName = etRecipientName.getText().toString(); 134 | final String senderEmail = etSenderEmail.getText().toString(); 135 | final String senderName = etSenderName.getText().toString(); 136 | final String subject = etSubject.getText().toString(); 137 | final String content = etContent.getText().toString(); 138 | final String replyToEmail = etReplyToEmail.getText().toString(); 139 | final String replyToName = getEtReplyToName.getText().toString(); 140 | 141 | if (recipientEmail.isEmpty() || senderEmail.isEmpty() || subject.isEmpty()) { 142 | showMissingField(); 143 | return; 144 | } 145 | 146 | final SendGridMail mail = new SendGridMail(); 147 | mail.addRecipient(recipientEmail, recipientName); 148 | mail.setFrom(senderEmail, senderName); 149 | mail.setSubject(subject); 150 | 151 | if (!content.isEmpty()) mail.setContent(content); 152 | 153 | if (!replyToEmail.equals("")) { 154 | mail.setReplyTo(replyToEmail, replyToName); 155 | } 156 | 157 | try { 158 | if (!attachments.isEmpty()) 159 | for (File file : attachments) 160 | mail.addAttachment(file); 161 | 162 | if (!uris.isEmpty()) 163 | for (Uri uri : uris) 164 | mail.addAttachment(getApplicationContext(), uri); 165 | } catch (IOException e) { 166 | e.printStackTrace(); 167 | } 168 | 169 | if (!TEMPLATE_ID.isEmpty()) { 170 | mail.setTemplateId(TEMPLATE_ID); 171 | // try { 172 | // mail.setDynamicTemplateData(getTemplatePayload()); 173 | // } catch (JSONException e) { 174 | // e.printStackTrace(); 175 | // } 176 | } 177 | 178 | send(mail); 179 | } 180 | 181 | private JSONObject getTemplatePayload() throws JSONException { 182 | final JSONObject jsonObject = new JSONObject(); 183 | jsonObject.put("field_one", "Hello this is field one"); 184 | jsonObject.put("field_two", "Hello this is field two"); 185 | jsonObject.put("field_three", "Hello this is field three"); 186 | jsonObject.put("image_text", "Hello this is image text"); 187 | return jsonObject; 188 | } 189 | 190 | private void send(SendGridMail mail) { 191 | final SendTask task = new SendTask(sendGrid); 192 | try { 193 | SendGridResponse response = task.send(mail); 194 | onResponse(response); 195 | } catch (ExecutionException e) { 196 | e.printStackTrace(); 197 | } catch (InterruptedException e) { 198 | e.printStackTrace(); 199 | } catch (Exception e) { 200 | throw new RuntimeException(e); 201 | } 202 | 203 | // disposable = Single.fromCallable(sendGrid.send(mail)) 204 | // .subscribeOn(Schedulers.io()) 205 | // .observeOn(AndroidSchedulers.mainThread()) 206 | // .subscribe(this::onResponse); 207 | } 208 | 209 | private void onResponse(SendGridResponse response) { 210 | if (response.isSuccessful()) 211 | Toast.makeText(getApplicationContext(), 212 | "Email sent successfully", 213 | Toast.LENGTH_SHORT) 214 | .show(); 215 | else 216 | Toast.makeText(getApplicationContext(), 217 | "Error " + response.getCode() + " while sending email: " + response.getErrorMessage(), 218 | Toast.LENGTH_SHORT) 219 | .show(); 220 | 221 | clearAttachments(); 222 | } 223 | 224 | private void addAttachment() { 225 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 226 | intent.setType("*/*"); 227 | startActivityForResult(intent, REQUEST_CODE); 228 | } 229 | 230 | private void showMissingField() { 231 | Toast.makeText(getApplicationContext(), "Required fields missing", Toast.LENGTH_SHORT).show(); 232 | } 233 | 234 | @Override 235 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 236 | super.onActivityResult(requestCode, resultCode, data); 237 | if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) { 238 | uris.add(data.getData()); 239 | // attachments.add(getFileFromUri(data.getData())); 240 | setAttachmentCount(); 241 | } 242 | } 243 | 244 | private File getFileFromUri(Uri uri) { 245 | try { 246 | return FileUtil.from(getApplicationContext(), uri); 247 | } catch (IOException e) { 248 | e.printStackTrace(); 249 | } 250 | return new File(""); 251 | } 252 | 253 | @Override 254 | protected void onDestroy() { 255 | super.onDestroy(); 256 | if (disposable != null) disposable.dispose(); 257 | } 258 | 259 | @Override 260 | protected void onStop() { 261 | super.onStop(); 262 | final SharedPreferences.Editor editor = sharedPreferences.edit(); 263 | 264 | editor.putString(PREFERENCE_RECIPIENT_EMAIL, etRecipientEmail.getText().toString()); 265 | editor.putString(PREFERENCE_RECIPIENT_NAME, etRecipientName.getText().toString()); 266 | editor.putString(PREFERENCE_SENDER_EMAIL, etSenderEmail.getText().toString()); 267 | editor.putString(PREFERENCE_SENDER_NAME, etSenderName.getText().toString()); 268 | editor.putString(PREFERENCE_SUBJECT, etSubject.getText().toString()); 269 | editor.putString(PREFERENCE_CONTENT, etContent.getText().toString()); 270 | 271 | editor.apply(); 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /testapp/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /testapp/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 13 | 14 | 26 | 27 | 39 | 40 | 52 | 53 | 65 | 66 | 80 | 81 | 93 | 94 | 105 | 106 | 116 | 117 | 127 | 128 | 138 | 139 | 151 | 152 | 164 | 165 |