├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── io │ └── bitbucket │ └── pablo127 │ └── gmail │ ├── Main.java │ └── service │ └── google │ ├── GmailCredentials.java │ ├── GmailService.java │ └── GmailServiceImpl.java └── test └── java └── io └── bitbucket └── pablo127 └── gmail └── service └── google └── GmailServiceImplTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /.gradle 2 | /.idea 3 | /build 4 | /out -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Paweł Świderski 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gmail-api-sample 2 | Sending emails with google API 3 | 4 | Tutorial for this repo is available on my blog: https://medium.com/@pablo127/sending-emails-from-java-app-with-gmail-api-eac23ca0eb5 5 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'io.bitbucket.pablo127' 2 | version '1.0.0-SNAPSHOT' 3 | 4 | apply plugin: 'java' 5 | 6 | sourceCompatibility = 1.8 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | compile 'org.projectlombok:lombok:1.16.8' 14 | 15 | compile 'javax.mail:mail:1.4.7' 16 | compile 'com.google.api-client:google-api-client:1.23.0' 17 | compile 'com.google.apis:google-api-services-gmail:v1-rev82-1.23.0' 18 | compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0' 19 | 20 | testCompile 'junit:junit:4.12' 21 | testCompile 'org.assertj:assertj-core:2.9.0' 22 | testCompile 'org.mockito:mockito-core:1.10.19' 23 | testCompile 'org.powermock:powermock-api-mockito:1.6.4' 24 | testCompile 'org.powermock:powermock-core:1.6.4' 25 | testCompile 'org.powermock:powermock-module-junit4:1.6.4' 26 | } 27 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plswiderski/gmail-api-sample/671e4355832c51414d610bb7f08191b302fa4bbc/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Mar 18 12:22:54 CET 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip 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 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'gmail' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/io/bitbucket/pablo127/gmail/Main.java: -------------------------------------------------------------------------------- 1 | package io.bitbucket.pablo127.gmail; 2 | 3 | import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 4 | import io.bitbucket.pablo127.gmail.service.google.GmailCredentials; 5 | import io.bitbucket.pablo127.gmail.service.google.GmailService; 6 | import io.bitbucket.pablo127.gmail.service.google.GmailServiceImpl; 7 | 8 | import javax.mail.MessagingException; 9 | import java.io.IOException; 10 | import java.security.GeneralSecurityException; 11 | 12 | public class Main { 13 | 14 | public static void main(String[] args) { 15 | try { 16 | GmailService gmailService = new GmailServiceImpl(GoogleNetHttpTransport.newTrustedTransport()); 17 | gmailService.setGmailCredentials(GmailCredentials.builder() 18 | .userEmail("YOUR_EMAIL@gmail.com") 19 | .clientId("1078329436949-rspqf1hkbedrqavvcakn8k6l6qd9asnl.apps.googleusercontent.com") 20 | .clientSecret("7Axm_PMdL3lppLdkA-MmPo7h") 21 | .accessToken("ya29.GluCBY6YE-TzEU2-F86sRl_Gq5QyPmUNW2wEV0MynFN-L3HK2AHEUD09pknXfrvk8UY6NYnGwuCIxAh97s6ipVylgwoNIsxLs7uouIBqj8vWiAODGiS2a1ZDNa8D") 22 | .refreshToken("1/XyMnZb4UfU8WDt6SnHIeE3wFTPyTAg2K16ZA7NIF0bY") 23 | .build()); 24 | 25 | gmailService.sendMessage("RECIPIENT_EMAIL@gmail.com", "Subject", "body text"); 26 | } catch (GeneralSecurityException | IOException | MessagingException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/bitbucket/pablo127/gmail/service/google/GmailCredentials.java: -------------------------------------------------------------------------------- 1 | package io.bitbucket.pablo127.gmail.service.google; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Builder 7 | @Data 8 | public class GmailCredentials { 9 | private final String userEmail; 10 | private final String clientId; 11 | private final String clientSecret; 12 | private final String accessToken; 13 | private final String refreshToken; 14 | } -------------------------------------------------------------------------------- /src/main/java/io/bitbucket/pablo127/gmail/service/google/GmailService.java: -------------------------------------------------------------------------------- 1 | package io.bitbucket.pablo127.gmail.service.google; 2 | 3 | import javax.mail.MessagingException; 4 | import java.io.IOException; 5 | 6 | public interface GmailService { 7 | void setGmailCredentials(GmailCredentials gmailCredentials); 8 | 9 | boolean sendMessage(String recipientAddress, String subject, String body) throws MessagingException, IOException; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/bitbucket/pablo127/gmail/service/google/GmailServiceImpl.java: -------------------------------------------------------------------------------- 1 | package io.bitbucket.pablo127.gmail.service.google; 2 | 3 | import com.google.api.client.auth.oauth2.Credential; 4 | import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 5 | import com.google.api.client.http.HttpTransport; 6 | import com.google.api.client.json.JsonFactory; 7 | import com.google.api.client.json.jackson2.JacksonFactory; 8 | import com.google.api.client.util.Base64; 9 | import com.google.api.services.gmail.Gmail; 10 | import com.google.api.services.gmail.model.Message; 11 | 12 | import javax.mail.MessagingException; 13 | import javax.mail.Session; 14 | import javax.mail.internet.InternetAddress; 15 | import javax.mail.internet.MimeMessage; 16 | import java.io.ByteArrayOutputStream; 17 | import java.io.IOException; 18 | import java.util.Properties; 19 | 20 | public final class GmailServiceImpl implements GmailService { 21 | 22 | private static final String APPLICATION_NAME = "YOUR_APP_NAME"; 23 | 24 | private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 25 | 26 | private final HttpTransport httpTransport; 27 | private GmailCredentials gmailCredentials; 28 | 29 | public GmailServiceImpl(HttpTransport httpTransport) { 30 | this.httpTransport = httpTransport; 31 | } 32 | 33 | @Override 34 | public void setGmailCredentials(GmailCredentials gmailCredentials) { 35 | this.gmailCredentials = gmailCredentials; 36 | } 37 | 38 | @Override 39 | public boolean sendMessage(String recipientAddress, String subject, String body) throws MessagingException, 40 | IOException { 41 | Message message = createMessageWithEmail( 42 | createEmail(recipientAddress, gmailCredentials.getUserEmail(), subject, body)); 43 | 44 | return createGmail().users() 45 | .messages() 46 | .send(gmailCredentials.getUserEmail(), message) 47 | .execute() 48 | .getLabelIds().contains("SENT"); 49 | } 50 | 51 | private Gmail createGmail() { 52 | Credential credential = authorize(); 53 | return new Gmail.Builder(httpTransport, JSON_FACTORY, credential) 54 | .setApplicationName(APPLICATION_NAME) 55 | .build(); 56 | } 57 | 58 | private MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException { 59 | MimeMessage email = new MimeMessage(Session.getDefaultInstance(new Properties(), null)); 60 | email.setFrom(new InternetAddress(from)); 61 | email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); 62 | email.setSubject(subject); 63 | email.setText(bodyText); 64 | return email; 65 | } 66 | 67 | private Message createMessageWithEmail(MimeMessage emailContent) throws MessagingException, IOException { 68 | ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 69 | emailContent.writeTo(buffer); 70 | 71 | return new Message() 72 | .setRaw(Base64.encodeBase64URLSafeString(buffer.toByteArray())); 73 | } 74 | 75 | private Credential authorize() { 76 | return new GoogleCredential.Builder() 77 | .setTransport(httpTransport) 78 | .setJsonFactory(JSON_FACTORY) 79 | .setClientSecrets(gmailCredentials.getClientId(), gmailCredentials.getClientSecret()) 80 | .build() 81 | .setAccessToken(gmailCredentials.getAccessToken()) 82 | .setRefreshToken(gmailCredentials.getRefreshToken()); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/test/java/io/bitbucket/pablo127/gmail/service/google/GmailServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package io.bitbucket.pablo127.gmail.service.google; 2 | 3 | import com.google.api.client.auth.oauth2.ClientParametersAuthentication; 4 | import com.google.api.client.auth.oauth2.Credential; 5 | import com.google.api.client.testing.http.MockHttpTransport; 6 | import com.google.api.client.util.Base64; 7 | import com.google.api.services.gmail.Gmail; 8 | import com.google.api.services.gmail.model.Message; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | import org.mockito.ArgumentMatcher; 13 | import org.powermock.core.classloader.annotations.PrepareForTest; 14 | import org.powermock.modules.junit4.PowerMockRunner; 15 | 16 | import javax.mail.Address; 17 | import javax.mail.MessagingException; 18 | import javax.mail.Session; 19 | import javax.mail.internet.InternetAddress; 20 | import javax.mail.internet.MimeMessage; 21 | import java.io.ByteArrayInputStream; 22 | import java.io.IOException; 23 | import java.util.Arrays; 24 | import java.util.Collections; 25 | import java.util.Properties; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | import static org.assertj.core.api.Assertions.fail; 29 | import static org.mockito.Matchers.eq; 30 | import static org.mockito.Mockito.*; 31 | import static org.powermock.api.mockito.PowerMockito.mockStatic; 32 | import static org.powermock.api.mockito.PowerMockito.whenNew; 33 | 34 | @RunWith(PowerMockRunner.class) 35 | @PrepareForTest({GmailServiceImpl.class, Gmail.class}) 36 | public class GmailServiceImplTest { 37 | 38 | private static final String RECIPIENT_ADDRESS = "receiver@gmail.com"; 39 | private static final String SUBJECT = "SUBJECT"; 40 | private static final String BODY = "BODY"; 41 | 42 | private static final GmailCredentials GMAIL_CREDENTIALS = GmailCredentials.builder() 43 | .userEmail("userEmail@gmail.com") 44 | .clientId("clientId") 45 | .clientSecret("clientSecret") 46 | .accessToken("accessToken") 47 | .refreshToken("refreshToken") 48 | .build(); 49 | 50 | private GmailServiceImpl gmailServiceImpl; 51 | 52 | private MockHttpTransport httpTransport; 53 | private Gmail.Users.Messages messages; 54 | 55 | @Before 56 | public void setUp() throws Exception { 57 | httpTransport = new MockHttpTransport(); 58 | gmailServiceImpl = new GmailServiceImpl(httpTransport); 59 | gmailServiceImpl.setGmailCredentials(GMAIL_CREDENTIALS); 60 | 61 | messages = mockMessages(mockUsers(mockGmail())); 62 | } 63 | 64 | @Test 65 | public void sendMessage() throws Exception { 66 | Gmail.Users.Messages.Send send = mockSend(messages, true); 67 | 68 | assertThat(gmailServiceImpl.sendMessage(RECIPIENT_ADDRESS, SUBJECT, BODY)).isTrue(); 69 | verify(send).execute(); 70 | } 71 | 72 | @Test 73 | public void sendMessage_notSent() throws Exception { 74 | Gmail.Users.Messages.Send send = mockSend(messages, false); 75 | 76 | assertThat(gmailServiceImpl.sendMessage(RECIPIENT_ADDRESS, SUBJECT, BODY)).isFalse(); 77 | verify(send).execute(); 78 | } 79 | 80 | private Gmail.Users.Messages.Send mockSend(Gmail.Users.Messages messages, boolean sent) throws IOException { 81 | Gmail.Users.Messages.Send send = mock(Gmail.Users.Messages.Send.class); 82 | doReturn(send).when(messages) 83 | .send(eq(GMAIL_CREDENTIALS.getUserEmail()), argThat(new ArgumentMatcher() { 84 | @Override 85 | public boolean matches(Object argument) { 86 | try { 87 | return matchMessage((Message) argument); 88 | } catch (IOException | MessagingException e) { 89 | fail("Error occurred while matching message", e); 90 | return false; 91 | } 92 | } 93 | })); 94 | 95 | doReturn(new Message().setLabelIds(Collections.singletonList(sent ? "SENT" : ""))).when(send).execute(); 96 | return send; 97 | } 98 | 99 | private Gmail.Users.Messages mockMessages(Gmail.Users users) { 100 | Gmail.Users.Messages messages = mock(Gmail.Users.Messages.class); 101 | doReturn(messages).when(users).messages(); 102 | return messages; 103 | } 104 | 105 | private Gmail.Users mockUsers(Gmail gmail) { 106 | Gmail.Users users = mock(Gmail.Users.class); 107 | doReturn(users).when(gmail).users(); 108 | return users; 109 | } 110 | 111 | private Gmail mockGmail() throws Exception { 112 | mockStatic(Gmail.class); 113 | Gmail gmail = mock(Gmail.class); 114 | whenNew(Gmail.class).withParameterTypes(Gmail.Builder.class) 115 | .withArguments(argThat(new ArgumentMatcher() { 116 | @Override 117 | public boolean matches(Object argument) { 118 | Gmail.Builder builder = (Gmail.Builder) argument; 119 | Credential credential = (Credential) builder.getHttpRequestInitializer(); 120 | return matchMainBuilderProperties(builder) && matchCredentialProperties(credential); 121 | } 122 | })) 123 | .thenReturn(gmail); 124 | return gmail; 125 | } 126 | 127 | private boolean matchMessage(Message message) throws IOException, MessagingException { 128 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.decodeBase64(message.getRaw())); 129 | Session session = Session.getDefaultInstance(new Properties(), null); 130 | 131 | MimeMessage mimeMessage = new MimeMessage(session, byteArrayInputStream); 132 | return Arrays.equals(mimeMessage.getFrom(), 133 | new Address[]{new InternetAddress(GMAIL_CREDENTIALS.getUserEmail())}) 134 | && Arrays.equals(mimeMessage.getRecipients(javax.mail.Message.RecipientType.TO), 135 | new Address[]{new InternetAddress(RECIPIENT_ADDRESS)}) 136 | && SUBJECT.equals(mimeMessage.getSubject()) 137 | && BODY.equals(mimeMessage.getContent()); 138 | } 139 | 140 | private boolean matchMainBuilderProperties(Gmail.Builder builder) { 141 | return builder.getTransport() == httpTransport 142 | && "YOUR_APP_NAME".equals(builder.getApplicationName()); 143 | } 144 | 145 | private boolean matchCredentialProperties(Credential credential) { 146 | return credential.getTransport() == httpTransport 147 | && GMAIL_CREDENTIALS.getAccessToken().equals(credential.getAccessToken()) 148 | && GMAIL_CREDENTIALS.getRefreshToken().equals(credential.getRefreshToken()) 149 | && matchClientAuthentication((ClientParametersAuthentication) credential.getClientAuthentication()); 150 | } 151 | 152 | private boolean matchClientAuthentication(ClientParametersAuthentication clientAuthentication) { 153 | return GMAIL_CREDENTIALS.getClientId().equals(clientAuthentication.getClientId()) 154 | && GMAIL_CREDENTIALS.getClientSecret().equals(clientAuthentication.getClientSecret()); 155 | } 156 | } --------------------------------------------------------------------------------