diff --git a/.env_sample b/.env_sample new file mode 100644 index 00000000..937e999d --- /dev/null +++ b/.env_sample @@ -0,0 +1 @@ +export SENDGRID_API_KEY='' diff --git a/.github/workflows/pr-lint.yml b/.github/workflows/pr-lint.yml new file mode 100644 index 00000000..2f5232b0 --- /dev/null +++ b/.github/workflows/pr-lint.yml @@ -0,0 +1,15 @@ +name: Lint PR +on: + pull_request_target: + types: [ opened, edited, synchronize, reopened ] + +jobs: + validate: + name: Validate title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v4 + with: + types: chore docs fix feat test misc + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml new file mode 100644 index 00000000..0a31274e --- /dev/null +++ b/.github/workflows/test-and-deploy.yml @@ -0,0 +1,101 @@ +name: Test and Deploy +on: + push: + branches: [ '*' ] + tags: [ '*' ] + pull_request: + branches: [ main ] + schedule: + # Run automatically at 8AM PST Monday-Friday + - cron: '0 15 * * 1-5' + workflow_dispatch: + +jobs: + test: + name: Test + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + matrix: + java: [ 8, 11 ] + env: + DOCKER_LOGIN: ${{ secrets.DOCKER_USERNAME && secrets.DOCKER_AUTH_TOKEN }} + steps: + - name: Checkout sendgrid-java + uses: actions/checkout@v2 + + - name: Login to Docker Hub + if: env.DOCKER_LOGIN + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_AUTH_TOKEN }} + + - name: Install Docker Compose + run: | + sudo apt-get update + sudo apt-get install -y docker-compose + + - name: Run Unit Tests + run: make test-docker version=${{ matrix.java }} + + deploy: + name: Deploy + if: success() && github.ref_type == 'tag' + needs: [ test ] + runs-on: ubuntu-latest + steps: + - name: Checkout sendgrid-java + uses: actions/checkout@v2 + + - name: Set up Sonatype Maven + uses: actions/setup-java@v2 + with: + java-version: 8 + distribution: temurin + server-id: central + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + gpg-passphrase: GPG_PASSPHRASE + + - name: Install dependencies and Build Release Artifacts + run: make install + + - name: Create GitHub Release + uses: sendgrid/dx-automator/actions/release@main + with: + assets: sendgrid-java.jar + footer: '**[Maven](https://mvnrepository.com/artifact/com.sendgrid/sendgrid-java/${version})**' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish to Maven + env: + MAVEN_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} + GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + run: mvn clean deploy -DskipTests=true -B -U -Prelease + + - name: Submit metric to Datadog + uses: sendgrid/dx-automator/actions/datadog-release-metric@main + env: + DD_API_KEY: ${{ secrets.DATADOG_API_KEY }} + + notify-on-failure: + name: Slack notify on failure + if: failure() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref_type == 'tag') + needs: [ test, deploy ] + runs-on: ubuntu-latest + steps: + - uses: rtCamp/action-slack-notify@v2 + env: + SLACK_COLOR: failure + SLACK_ICON_EMOJI: ':github:' + SLACK_MESSAGE: ${{ format('Test *{0}*, Deploy *{1}*, {2}/{3}/actions/runs/{4}', needs.test.result, needs.deploy.result, github.server_url, github.repository, github.run_id) }} + SLACK_TITLE: Action Failure - ${{ github.repository }} + SLACK_USERNAME: GitHub Actions + SLACK_MSG_AUTHOR: twilio-dx + SLACK_FOOTER: Posted automatically using GitHub Actions + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + MSG_MINIMAL: true diff --git a/.github/workflows/update-dependencies.yml b/.github/workflows/update-dependencies.yml new file mode 100644 index 00000000..eea77a93 --- /dev/null +++ b/.github/workflows/update-dependencies.yml @@ -0,0 +1,54 @@ +name: Update dependencies +on: + schedule: + # Run automatically at 7AM PST Tuesday + - cron: '0 14 * * 2' + workflow_dispatch: + +jobs: + update-dependencies-and-test: + name: Update Dependencies & Test + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + max-parallel: 1 + matrix: + java: [ 8, 11 ] + + steps: + - name: Checkout sendgrid-java + uses: actions/checkout@v2 + + - name: Updating semver dependencies + run: make update-deps + + - name: Run Unit Tests + run: make test-docker version=${{ matrix.java }} + + - name: Add & Commit + if: matrix.java == '11' + uses: EndBug/add-and-commit@v8.0.2 + env: + GITHUB_TOKEN: ${{ secrets.SG_JAVA_GITHUB_TOKEN }} + with: + add: 'pom.xml' + default_author: 'github_actions' + message: 'chore: update sendgrid-java dependencies' + + notify-on-failure: + name: Slack notify on failure + if: failure() + needs: [ update-dependencies-and-test ] + runs-on: ubuntu-latest + steps: + - uses: rtCamp/action-slack-notify@v2 + env: + SLACK_COLOR: failure + SLACK_ICON_EMOJI: ':github:' + SLACK_MESSAGE: ${{ format('Update dependencies *{0}*, {1}/{2}/actions/runs/{3}', needs.update-dependencies-and-test.result, github.server_url, github.repository, github.run_id) }} + SLACK_TITLE: Action Failure - ${{ github.repository }} + SLACK_USERNAME: GitHub Actions + SLACK_MSG_AUTHOR: twilio-dx + SLACK_FOOTER: Posted automatically using GitHub Actions + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + MSG_MINIMAL: true diff --git a/.gitignore b/.gitignore index e52e240b..12b0a405 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,14 @@ out .DS_Store repo gradle.properties -target \ No newline at end of file +target +*.class +examples/Example.java +.settings +.classpath +.project +.env +.vscode +sendgrid-java.jar +dependency-reduced-pom.xml +prism* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8a02d27a..00000000 --- a/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: java -jdk: -- oraclejdk8 -- oraclejdk7 -- openjdk7 -- openjdk6 -after_script: -- "./gradlew build" -- "./scripts/s3upload.sh" -env: - global: - - S3_POLICY: ewogICJleHBpcmF0aW9uIjogIjIxMDAtMDEtMDFUMTI6MDA6MDAuMDAwWiIsCiAgImNvbmRpdGlvbnMiOiBbCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCIgfSwKICAgIHsiYnVja2V0IjogInNlbmRncmlkLW9wZW4tc291cmNlIiB9LAogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInNlbmRncmlkLWphdmEvIl0sCiAgICBbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwgMjA0OCwgMjY4NDM1NDU2XSwKICAgIFsiZXEiLCAiJENvbnRlbnQtVHlwZSIsICJhcHBsaWNhdGlvbi96aXAiXQogIF0KfQo= - - secure: Iki1btwhG1nlyjnEMu90Oh/hoatFpPiiKkqpj7siLnlLp2xbBQ2003jRsn30I3Vujes2ugvzdlHqBJ9lDwRvfGrKXcLlRvYuDQ24N2YKquEiKHUxs+iMOzTQj6Sf64KL5O0aSZd1l5rjWgsQ0qqjHW9u3l5bUjqxzrhAI2Js37U= - - secure: Khi6a4z1lfZmDEDV738MOiWznRcTv5ILZUM+igEw2txX7PGX+B5909WridpAijTGiurJ6eda7jvsUgci8DTPQCXB18LD6N870hnPcSQkuI6zDAhKTx+w/ZsfPLWh28sP2CVzbqGdxaitZDKxRWaVmKnBZpyi8XI9UKjmyK2sjwE= - - secure: wKXAjjBgCLM4h++nP1xDQQtYU10JbwwynY0XB920SoQjI2Uu82cMPtkEXFWTpzyIS2hE5B3qvu75VHNdLqDUtek3e3lBg5k3SpYgGin20dg3SDEJrvA4vlvcApdQ132pMEWdDOVwzbXhm9+JTjALYbc3fX+VAQX1u5daPyeDGC4= -notifications: - hipchat: - rooms: - secure: kJyc36IRkovqK3JuMXJuBBkDFkDfZ9iAE8ZziszzL9zNsfY2fAQWDk4bMrFO0yYW9OwRXl0gT97HVYWBZFDhjtstUJxit0lpUB+TNIDw2lqCkOIPxGKgcBB9mDS795QyLJzletObP/guPxbzSNOGLa6+k4GbTtTMXRhjzN6lF0o= - template: - - '%{repository} - Build %{build_number} on branch %{branch} by %{author}: %{message} - View on GitHub' - format: html - notify: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 974bb5ef..0419d039 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,473 @@ # Change Log All notable changes to this project will be documented in this file. +[2024-09-18] Version 4.10.3 +--------------------------- +**Library - Chore** +- [PR #767](https://github.com/sendgrid/sendgrid-java/pull/767): move Bouncy Castle dependency to test scope. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-02-14] Version 4.10.2 +--------------------------- +**Library - Chore** +- [PR #745](https://github.com/sendgrid/sendgrid-java/pull/745): update jackson version and licence year. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2023-11-17] Version 4.10.1 +--------------------------- +**Library - Chore** +- [PR #744](https://github.com/sendgrid/sendgrid-java/pull/744): updates bouncy castle to 1.76 (latest 1.7x). Thanks to [@mrdziuban](https://github.com/mrdziuban)! +- [PR #741](https://github.com/sendgrid/sendgrid-java/pull/741): updates bouncy castle to 1.75 (latest 1.7x). Thanks to [@kebeda](https://github.com/kebeda)! + + +[2023-11-06] Version 4.10.0 +--------------------------- +**Library - Feature** +- [PR #743](https://github.com/sendgrid/sendgrid-java/pull/743): Add data residency for eu and global regions. Thanks to [@shrutiburman](https://github.com/shrutiburman)! + +**Library - Test** +- [PR #735](https://github.com/sendgrid/sendgrid-java/pull/735): Adding misc as PR type. Thanks to [@rakatyal](https://github.com/rakatyal)! + + +[2022-06-29] Version 4.9.3 +-------------------------- +**Library - Chore** +- [PR #727](https://github.com/sendgrid/sendgrid-java/pull/727): bump jackson-databind from 2.13.2 to 2.13.3. Thanks to [@dependabot](https://github.com/dependabot)! + + +[2022-05-18] Version 4.9.2 +-------------------------- +**Library - Docs** +- [PR #732](https://github.com/sendgrid/sendgrid-java/pull/732): Modify README.md in alignment with SendGrid Support. Thanks to [@garethpaul](https://github.com/garethpaul)! + +**Library - Chore** +- [PR #726](https://github.com/sendgrid/sendgrid-java/pull/726): security upgrade jackson-databind from 2.13.0 to 2.13.2. Thanks to [@tomoyaY](https://github.com/tomoyaY)! + +**Library - Fix** +- [PR #725](https://github.com/sendgrid/sendgrid-java/pull/725): override default gh token. Thanks to [@beebzz](https://github.com/beebzz)! + + +[2022-03-23] Version 4.9.1 +-------------------------- +**Library - Chore** +- [PR #723](https://github.com/sendgrid/sendgrid-java/pull/723): Security upgrade com.fasterxml.jackson.core:jackson-databind from 2.12.1 to 2.13.0. Thanks to [@svcprodsec-sendgrid](https://github.com/svcprodsec-sendgrid)! + + +[2022-03-09] Version 4.9.0 +-------------------------- +**Library - Chore** +- [PR #721](https://github.com/sendgrid/sendgrid-java/pull/721): push Datadog Release Metric upon deploy success. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Library - Feature** +- [PR #717](https://github.com/sendgrid/sendgrid-java/pull/717): add GH action to update dependencies. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + + +[2022-02-09] Version 4.8.3 +-------------------------- +**Library - Chore** +- [PR #716](https://github.com/sendgrid/sendgrid-java/pull/716): add gh release to workflow. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! +- [PR #715](https://github.com/sendgrid/sendgrid-java/pull/715): merge test and deploy workflows. Thanks to [@Hunga1](https://github.com/Hunga1)! + + +[2022-01-12] Version 4.8.2 +-------------------------- +**Library - Fix** +- [PR #713](https://github.com/sendgrid/sendgrid-java/pull/713): fix sendgrid-java unit tests. Thanks to [@beebzz](https://github.com/beebzz)! + +**Library - Chore** +- [PR #712](https://github.com/sendgrid/sendgrid-java/pull/712): update license year. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + + +[2021-12-01] Version 4.8.1 +-------------------------- +**Library - Chore** +- [PR #710](https://github.com/sendgrid/sendgrid-java/pull/710): fix pom for release. Thanks to [@eshanholtz](https://github.com/eshanholtz)! +- [PR #709](https://github.com/sendgrid/sendgrid-java/pull/709): migrate to github actions. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + + +[2021-11-03] Version 4.8.0 +-------------------------- +**Library - Fix** +- [PR #707](https://github.com/sendgrid/sendgrid-java/pull/707): Add missing bypass settings to MailSettings. Thanks to [@arkitex](https://github.com/arkitex)! + +**Library - Feature** +- [PR #706](https://github.com/sendgrid/sendgrid-java/pull/706): allow personalization of the From name and email for each email recipient. Thanks to [@beebzz](https://github.com/beebzz)! + + +[2021-10-18] Version 4.7.6 +-------------------------- +**Library - Docs** +- [PR #705](https://github.com/sendgrid/sendgrid-java/pull/705): improve signed webhook events docs. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + + +[2021-09-22] Version 4.7.5 +-------------------------- +**Library - Chore** +- [PR #703](https://github.com/sendgrid/sendgrid-java/pull/703): update docker. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + + +[2021-08-11] Version 4.7.4 +-------------------------- +**Library - Chore** +- [PR #694](https://github.com/sendgrid/sendgrid-java/pull/694): [Snyk] Security upgrade com.sendgrid:java-http-client from 4.3.6 to 4.3.7. Thanks to [@svcprodsec-sendgrid](https://github.com/svcprodsec-sendgrid)! + + +[2021-06-30] Version 4.7.3 +-------------------------- +**Library - Docs** +- [PR #679](https://github.com/sendgrid/sendgrid-java/pull/679): Fix number of free emails in README. Thanks to [@mjjs](https://github.com/mjjs)! + + +[2021-02-24] Version 4.7.2 +-------------------------- +**Library - Chore** +- [PR #671](https://github.com/sendgrid/sendgrid-java/pull/671): bump jackson.version from 2.10.2 to 2.12.1. Thanks to [@dependabot](https://github.com/dependabot)! + + +[2020-12-16] Version 4.7.1 +-------------------------- +**Library - Fix** +- [PR #657](https://github.com/sendgrid/sendgrid-java/pull/657): Utilize headers set on the Request object. Thanks to [@prputnam](https://github.com/prputnam)! + + +[2020-11-18] Version 4.7.0 +-------------------------- +**Library - Docs** +- [PR #656](https://github.com/sendgrid/sendgrid-java/pull/656): Fix broken link in readme. Thanks to [@KakeJopulsky](https://github.com/KakeJopulsky)! +- [PR #405](https://github.com/sendgrid/sendgrid-java/pull/405): Create use-cases directory. Thanks to [@jamietanna](https://github.com/jamietanna)! +- [PR #418](https://github.com/sendgrid/sendgrid-java/pull/418): Fixes Javadoc errors in Attachments.java. Thanks to [@pacbac](https://github.com/pacbac)! +- [PR #628](https://github.com/sendgrid/sendgrid-java/pull/628): Correct number of free emails. Thanks to [@twogood](https://github.com/twogood)! +- [PR #304](https://github.com/sendgrid/sendgrid-java/pull/304): Save attachment to Dropbox. Thanks to [@deepapanwar](https://github.com/deepapanwar)! +- [PR #357](https://github.com/sendgrid/sendgrid-java/pull/357): Fix code issues in examples/clients/clients.java. Thanks to [@pushkyn](https://github.com/pushkyn)! + +**Library - Feature** +- [PR #292](https://github.com/sendgrid/sendgrid-java/pull/292): Add helper for get unassigned IPs. Thanks to [@pushkyn](https://github.com/pushkyn)! + + +[2020-11-05] Version 4.6.8 +-------------------------- +**Library - Chore** +- [PR #651](https://github.com/sendgrid/sendgrid-java/pull/651): Fix PR link for PRs. Thanks to [@jsoref](https://github.com/jsoref)! +- [PR #650](https://github.com/sendgrid/sendgrid-java/pull/650): fix spelling typos. Thanks to [@jsoref](https://github.com/jsoref)! + + +[2020-10-14] Version 4.6.7 +-------------------------- +**Library - Docs** +- [PR #360](https://github.com/sendgrid/sendgrid-java/pull/360): reorganize examples. Thanks to [@derjayjay](https://github.com/derjayjay)! + + +[2020-09-28] Version 4.6.6 +-------------------------- +**Library - Docs** +- [PR #504](https://github.com/sendgrid/sendgrid-java/pull/504): Update documentation for GET /templates. Thanks to [@LinkedList](https://github.com/LinkedList)! + +**Library - Fix** +- [PR #649](https://github.com/sendgrid/sendgrid-java/pull/649): update the eventwebhook sample data, example, tests, and byte handling. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-09-16] Version 4.6.5 +-------------------------- +**Library - Docs** +- [PR #477](https://github.com/sendgrid/sendgrid-java/pull/477): Run *.md documents through Grammar.ly. Thanks to [@vinird](https://github.com/vinird)! + + +[2020-08-19] Version 4.6.4 +-------------------------- +**Library - Docs** +- [PR #491](https://github.com/sendgrid/sendgrid-java/pull/491): add contribution guide for first-timers. Thanks to [@daniloff200](https://github.com/daniloff200)! + +**Library - Test** +- [PR #496](https://github.com/sendgrid/sendgrid-java/pull/496): Add spotbugs and checkstyle maven plugins for Travis CI. Thanks to [@rosariopfernandes](https://github.com/rosariopfernandes)! + +**Library - Chore** +- [PR #644](https://github.com/sendgrid/sendgrid-java/pull/644): update GitHub branch references to use HEAD. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + + +[2020-08-05] Version 4.6.3 +-------------------------- +**Library - Chore** +- [PR #539](https://github.com/sendgrid/sendgrid-java/pull/539): tidied up a little. Thanks to [@RohanTalip](https://github.com/RohanTalip)! + +**Library - Docs** +- [PR #370](https://github.com/sendgrid/sendgrid-java/pull/370): breakup examples to their own files in examples/user/user.java. Thanks to [@rivenhk](https://github.com/rivenhk)! +- [PR #390](https://github.com/sendgrid/sendgrid-java/pull/390): Update README link to avoid redirection. Thanks to [@Rolstenhouse](https://github.com/Rolstenhouse)! + +**Library - Fix** +- [PR #643](https://github.com/sendgrid/sendgrid-java/pull/643): Replace `bcprov-jdk15to18` with `bcprov-jdk15on`. Thanks to [@Stephan202](https://github.com/Stephan202)! +- [PR #642](https://github.com/sendgrid/sendgrid-java/pull/642): remove the content verifier. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-07-22] Version 4.6.2 +-------------------------- +**Library - Chore** +- [PR #639](https://github.com/sendgrid/sendgrid-java/pull/639): migrate to new default sendgrid-oai branch. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Library - Docs** +- [PR #638](https://github.com/sendgrid/sendgrid-java/pull/638): add multi-recipient examples. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #637](https://github.com/sendgrid/sendgrid-java/pull/637): fix the kitchen sink example and link to it in the use cases doc. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-07-08] Version 4.6.1 +-------------------------- +**Library - Fix** +- [PR #635](https://github.com/sendgrid/sendgrid-java/pull/635): don't use dependency version ranges. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-06-10] Version 4.6.0 +-------------------------- +**Library - Feature** +- [PR #626](https://github.com/sendgrid/sendgrid-java/pull/626): add prism Docker setup. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-05-13] Version 4.5.0 +-------------------------- +**Library - Feature** +- [PR #622](https://github.com/sendgrid/sendgrid-java/pull/622): verify signature from event webhook. Thanks to [@anujs3](https://github.com/anujs3)! +- [PR #621](https://github.com/sendgrid/sendgrid-java/pull/621): add support for Twilio Email. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-04-15] Version 4.4.8 +-------------------------- +**Library - Fix** +- [PR #618](https://github.com/sendgrid/sendgrid-java/pull/618): correct the User-Agent casing. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-04-01] Version 4.4.7 +-------------------------- +**Library - Docs** +- [PR #617](https://github.com/sendgrid/sendgrid-java/pull/617): support verbiage for login issues. Thanks to [@adamchasetaylor](https://github.com/adamchasetaylor)! +- [PR #615](https://github.com/sendgrid/sendgrid-java/pull/615): fix link to jar file. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Library - Fix** +- [PR #612](https://github.com/sendgrid/sendgrid-java/pull/612): correct the serialization of Setting to include non-null values. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-03-18] Version 4.4.6 +-------------------------- +**Library - Docs** +- [PR #264](https://github.com/sendgrid/sendgrid-java/pull/264): Overhaul javadocs, using Oracle's styleguide. Thanks to [@jamierocks](https://github.com/jamierocks)! + +**Library - Chore** +- [PR #610](https://github.com/sendgrid/sendgrid-java/pull/610): fix JDK Travis failures. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2020-02-19] Version 4.4.5 +-------------------------- +**Library - Docs** +- [PR #540](https://github.com/sendgrid/sendgrid-java/pull/540): Update the link for Google's Style Guide. Thanks to [@RohanTalip](https://github.com/RohanTalip)! + + +[2020-02-08] Version 4.4.4 +-------------------------- +**Library - Fix** +- [PR #608](https://github.com/sendgrid/sendgrid-java/pull/608): update release jar. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + + +[2020-02-05] Version 4.4.3 +-------------------------- +**Library - Docs** +- [PR #604](https://github.com/sendgrid/sendgrid-java/pull/604): Fix GitHub spelling. Thanks to [@friederbluemle](https://github.com/friederbluemle)! +- [PR #534](https://github.com/sendgrid/sendgrid-java/pull/534): Fix whitespace errors and typos. Thanks to [@friederbluemle](https://github.com/friederbluemle)! +- [PR #402](https://github.com/sendgrid/sendgrid-java/pull/402): Add Code Review to Contributing.md. Thanks to [@derekneuland](https://github.com/derekneuland)! +- [PR #603](https://github.com/sendgrid/sendgrid-java/pull/603): baseline all the templated markdown docs. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #387](https://github.com/sendgrid/sendgrid-java/pull/387): makes Environmental Variables a sub topic in CONTRIBUTING.md. Thanks to [@thepriefy](https://github.com/thepriefy)! +- [PR #516](https://github.com/sendgrid/sendgrid-java/pull/516): fix a minor type in README. Thanks to [@anuragsachdeva28](https://github.com/anuragsachdeva28)! +- [PR #590](https://github.com/sendgrid/sendgrid-java/pull/590): fix typo in README. Thanks to [@brianjester](https://github.com/brianjester)! + +**Library - Chore** +- [PR #542](https://github.com/sendgrid/sendgrid-java/pull/542): Removed the apiKey instance variable as it wasn't being used. Thanks to [@RohanTalip](https://github.com/RohanTalip)! +- [PR #563](https://github.com/sendgrid/sendgrid-java/pull/563): Remove unnecessary access modifiers on interface methods. Thanks to [@ethanwood17](https://github.com/ethanwood17)! +- [PR #602](https://github.com/sendgrid/sendgrid-java/pull/602): Bump jackson.version from 2.9.9 to 2.10.2. Thanks to [@dependabot](https://github.com/dependabot)! + + +[2020-02-01] Version 4.4.2 +-------------------------- +**Library - Chore** +- [PR #471](https://github.com/sendgrid/sendgrid-java/pull/471): Update build.gradle. Thanks to [@doilio](https://github.com/doilio)! +- [PR #557](https://github.com/sendgrid/sendgrid-java/pull/557): Update Jackson dependencies to the latest version. Thanks to [@wkurniawan07](https://github.com/wkurniawan07)! +- [PR #574](https://github.com/sendgrid/sendgrid-java/pull/574): maven-compiler-plugin 3.8.1. Thanks to [@sullis](https://github.com/sullis)! +- [PR #599](https://github.com/sendgrid/sendgrid-java/pull/599): prep the repo for automated release. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + + +[2019-05-20] Version 4.4.1 +--------------------------- +### Fix +- 4.4.0 release not deployed properly to Maven + +## [4.4.0] - 2019-05-20 +### Added +- [PR #500](https://github.com/sendgrid/sendgrid-java/pull/500/files): Update CONTRIBUTING.md - using gitflow workflow, development branch instead of main -- BIG thanks to [Alex](https://github.com/pushkyn) +- [PR #521](https://github.com/sendgrid/sendgrid-java/pull/521/files): Updating prerequisites -- BIG thanks to [Rishabh](https://github.com/Rishabh04-02) +- [PR #495](https://github.com/sendgrid/sendgrid-java/pull/495/files): Add ability to impersonate subusers -- BIG thanks to [Rohit Tarachandani](https://github.com/Rohit-T) +- [PR #569](https://github.com/sendgrid/sendgrid-java/pull/495/files): Twilio Branding + CLA Policy Update + +### Fix +- [PR #497](https://github.com/sendgrid/sendgrid-java/pull/497): USE_CASES.md was missing the subject in the template and the dynamic data for the subject -- BIG thanks to [Kyle Roberts](https://github.com/kylearoberts) +- [PR #306](https://github.com/sendgrid/sendgrid-java/pull/306): Java packages were not corresponding to the actual location of classes, +all packages were update to match class location -- BIG thanks to [Bojan Trajkovski](https://github.com/btrajkovski) +- [PR #544](https://github.com/sendgrid/sendgrid-java/pull/544): Remove references to "Whitelabel" -- BIG thanks to [Chandler Weiner](https://github.com/crweiner) +- [PR #507](https://github.com/sendgrid/sendgrid-java/pull/507): Update TROUBLESHOOTING.md broken link -- BIG thanks to [Andrew Joshua Loria](https://github.com/ajloria) + +## [4.3.0] - 2018-10-11 +### Added +- [PR #449](https://github.com/sendgrid/sendgrid-java/pull/449/files): Dynamic Templates support -- BIG thanks to [Marcus Vinícius](https://github.com/Markuus13) +- [PR #451](https://github.com/sendgrid/sendgrid-java/pull/451/files): Added CodeTriage tag -- BIG thanks to [Anshul Singhal](https://github.com/af4ro) +- [PR #453](https://github.com/sendgrid/sendgrid-java/pull/453/files): Documentation readability update -- BIG thanks to [Anshul Singhal](https://github.com/af4ro) +- [PR #461](https://github.com/sendgrid/sendgrid-java/pull/461/files): Update README to use implementation instead of compile -- BIG thanks to [Rosário Pereira Fernandes](https://github.com/rosariopfernandes) +- [PR #463](https://github.com/sendgrid/sendgrid-java/pull/463/files): Link to the online version of CLA in README.md -- BIG thanks to [Bharat Raghunathan](https://github.com/Bharat123rox) + +### Fix +- [PR #358](https://github.com/sendgrid/sendgrid-java/pull/358): Fixing similar code issue in examples/ips/ips.java -- BIG thanks to [Julian Jacques Maurer](https://github.com/derjayjay) +- [PR #475](https://github.com/sendgrid/sendgrid-java/pull/475): Fix formatting of README in examples/accesssettings -- BIG thanks to [Nathan Seebarran](https://github.com/nathan78906) + +## [4.2.1] - 2018-05-08 +### Security Fix +- Update to the latest Jackson recommended dependency, based on [this article](https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062). + +## [4.2.0] - 2018-05-04 +### Added +- [PR #275](https://github.com/sendgrid/sendgrid-java/pull/275/files): Add a way to verify that the content doesn't contain sensitive information -- BIG thanks to [Diego Camargo](https://github.com/belfazt) +- [PR #249](https://github.com/sendgrid/sendgrid-java/pull/249): Add optional rate limit support -- BIG thanks to [Andy Trimble](https://github.com/andy-trimble) +- [PR #379](https://github.com/sendgrid/sendgrid-java/pull/379): Break up the examples in examples/subusers/subusers.java to their own files -- BIG thanks to [huytranrjc](https://github.com/huytranrjc) +- [PR #365](https://github.com/sendgrid/sendgrid-java/pull/365): Test to check year in license file -- BIG thanks to [Alex](https://github.com/pushkyn) +- [PR #345](https://github.com/sendgrid/sendgrid-java/pull/345): Add .codeclimate.yml file -- BIG thanks to [Rostyslav Zatserkovnyi](https://github.com/rzats) +- [PR #319](https://github.com/sendgrid/sendgrid-java/pull/319): Add .env_sample file -- BIG thanks to [Thiago Barbato](https://github.com/thiagobbt) +- [PR #223](https://github.com/sendgrid/sendgrid-java/pull/223): The license file is now in the release jar -- BIG thanks to [sccalabr](https://github.com/sccalabr) +- [PR #224](https://github.com/sendgrid/sendgrid-java/pull/224): Adding SendGridApi interface -- BIG thanks to [sccalabr](https://github.com/sccalabr) + +### Fix +- [PR #410](https://github.com/sendgrid/sendgrid-java/pull/410): Update Jackson dependencies to the latest version -- BIG thanks to [Dmitry Avershin](https://github.com/dmitraver) +- [PR #380](https://github.com/sendgrid/sendgrid-java/pull/380): Fix "similar-code" issue in examples/whitelabel/ips.java -- BIG thanks to [huytranrjc](https://github.com/huytranrjc) +- [PR #255](https://github.com/sendgrid/sendgrid-java/pull/225): Fix Mail deserialization issue -- BIG thanks to [sccalabr](https://github.com/sccalabr) +- [PR #359](https://github.com/sendgrid/sendgrid-java/pull/359): Fix code issue in examples/suppression/suppression.java -- BIG thanks to [Alex](https://github.com/pushkyn) +- [PR #228](https://github.com/sendgrid/sendgrid-java/pull/228): Changes serialization type from default to non-empty -- BIG thanks to [Dmitry Avershin](https://github.com/dmitraver) +- [PR #373](https://github.com/sendgrid/sendgrid-java/pull/373): Fix file_lines issue in examples/mailsettings/mailsettings.java -- BIG thanks to [Mithun Sasidharan](https://github.com/mithunsasidharan) + + +## [4.1.2] - 2017-10-30 +### Added +- PR #220 Alway serialize click-tracking parameters. +- BIG thanks to [Mattia Barbon](https://github.com/mbarbon) + +## [4.1.1] - 2017-10-10 +### Added +- PR #247 Added Javadocs. +- BIG thanks to [Andy Trimble](https://github.com/andy-trimble) + +## [4.1.0] - 2017-08-16 +### Added +- PR #211 Return empty collections in place of nulls +- BIG thanks to [Antonio Bucciol](https://github.com/TBuc) + +## [4.0.1] - 2017-05-22 +### Fix +- PR #199 Return correct Email in getFrom +- BIG thanks to [Jared Dellitt](https://github.com/jareddellitt) + +## [4.0.0] - 2017-04-18 +### BREAKING CHANGE +- PR #162 Update java HTTP client dependency to [4.1.0 from 2.3.4](https://github.com/sendgrid/java-http-client/releases) +- BIG thanks to [Diego Camargo](https://github.com/belfazt) for the pull request! +- The breaking change is that variables that were public are now private and accessible only via getters and setters +- The `Request` object attributes are now only accessible through getters/setters +- `request.method` is now `request.setMethod(string)` +- `request.endpoint` is now `request.setEndpoint(string)` +- `request.body` is now `request.setBody(string)` +- The `Response` object attributes are now only accessible through getters/setters +- `response.statusCode` is now `response.getStatusCode()` +- `response.body` is now `response.getBody()` +- `response.headers` is now `response.getHeaders()` +- Adding a query parameter goes from: + +```java +Map queryParams = new HashMap(); +request.addQueryParam("limit", "1"); +queryParams.put("limit", "1"); +request.queryParams = queryParams; +``` + +to: + +```java +request.addQueryParam("limit", "1"); +``` + +## [3.2.1] - 2017-04-13 +### Added +- PR #175 +- Simplified method `makeCall()`. +- BIG thanks to [Rafał Wrzeszcz](https://github.com/rafalwrzeszcz) for the pull request! + +## [3.2.0] - 2017-03-22 +### Added +- PR #160 +- [Enhancement] Adds an attachment builder that supports InputStream content +- BIG thanks to [Dmitry Avershin](https://github.com/dmitraver) for the pull request! + +## [3.1.0] - 2016-10-11 +### Added +- PR #158, Solves #138 +- [Enhancement] allow using custom Client, HTTP proxy support +- BIG thanks to [David Maicher](https://github.com/dmaicher) for the pull request! + +## [3.0.9] - 2016-08-24 +### Added +- Table of Contents in the README +- Added a [USE_CASES.md](USE_CASES.md) section, with the first use case example for transactional templates + +## [3.0.8] - 2016-08-09 +### Fixed +- Updated dependency for [java-http-client](https://github.com/sendgrid/java-http-client/releases/tag/v2.3.4) +- [Pull #7](https://github.com/sendgrid/java-http-client/pull/7): Fix Response Charset to UTF-8 +- Fixes [issue #6](https://github.com/sendgrid/java-http-client/issues/6): Multi-byte character got garbled on received mail +- BIG thanks to [Yoichi Kikuta](https://github.com/kikutaro) for the pull request! + +## [3.0.7] - 2016-08-08 +### Added +- Updated dependency for [java-http-client](https://github.com/sendgrid/java-http-client/releases/tag/v2.3.3) +- Pull request [#11](https://github.com/sendgrid/java-http-client/pull/11) +- Solves [issue #10](https://github.com/sendgrid/java-http-client/issues/10): Improve Error Handling +- Now error messages are passed through from the SendGrid server +- BIG thanks to [shuron](https://github.com/shuron) / [Alexander Holbreich](https://github.com/aholbreich) for the pull request! + +## [3.0.6] - 2016-07-26 +### Added +- [Troubleshooting](TROUBLESHOOTING.md) section + +## [3.0.5] - 2016-07-20 +### Added +- README updates +- Update introduction blurb to include information regarding our forward path +- Update the v3 /mail/send example to include non-helper usage +- Update the generic v3 example to include non-fluent interface usage + +## [3.0.4] - 2016-07-19 +### Fixed +- [Fix for issue #120](https://github.com/sendgrid/sendgrid-java/issues/120): Unsupported Media Type if the subject has letters with an accent (like 'é' ) +- Updated [java-http-client](https://github.com/sendgrid/java-http-client) dependency to [2.3.2](https://github.com/sendgrid/java-http-client/releases/tag/v2.3.2) + +## [3.0.3] - 2016-07-12 +### Added +- Update docs, unit tests and examples to include Sender ID + +## [3.0.2] - 2016-07-05 +### Updated +- Content based on our updated [Swagger/OAI doc](https://github.com/sendgrid/sendgrid-oai) + +## [3.0.1] - 2016-06-28 +### Fixed +- Accept header via [Get Satisfaction](https://community.sendgrid.com/sendgrid/topics/sendgrid-v3-webapi-issue-with-accept-header-response-406-not-acceptable) + +## [3.0.0] - 2016-06-13 +### Added +- Breaking change to support the v3 Web API +- New HTTP client +- v3 Mail Send helper + ## [2.2.2] - 2015-5-23 ### Fixed -- Subsitution orders being swapped via [#65](https://github.com/sendgrid/sendgrid-java/pull/65) +- Substitution orders being swapped via [#65](https://github.com/sendgrid/sendgrid-java/pull/65) ## [2.2.1] - 2015-5-14 ### Changed diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..2f0727ed --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,73 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at open-source@twilio.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..c97a921f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,170 @@ +Hello! Thank you for choosing to help contribute to one of the Twilio SendGrid open source libraries. There are many ways you can contribute and help is always welcome. We simply ask that you follow the following contribution policies. + +**All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under.** + +- [Feature Request](#feature-request) +- [Improvements to the Codebase](#improvements-to-the-codebase) + - [Development Environment](#development-environment) + - [Install and Run Locally](#install-and-run-locally) + - [Prerequisites](#prerequisites) + - [Initial setup:](#initial-setup) +- [Environment Variables](#environment-variables) + - [Execute:](#execute) +- [Understanding the Code Base](#understanding-the-code-base) +- [Testing](#testing) +- [Style Guidelines & Naming Conventions](#style-guidelines--naming-conventions) +- [Creating a Pull Request](#creating-a-pull-request) +- [Code Reviews](#code-reviews) + +There are a few ways to contribute, which we'll enumerate below: + + +## Improvements to the Codebase + +We welcome direct contributions to the sendgrid-java code base. Thank you! + +Please note that we utilize the [Gitflow Workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) for Git to help keep project development organized and consistent. + +### Development Environment ### + +#### Install and Run Locally #### + +##### Prerequisites ##### + +- Java 8 or 11 +- [java-http-client](https://github.com/sendgrid/java-http-client) + +##### Initial setup: ##### + +```bash +git clone https://github.com/sendgrid/sendgrid-java.git +cd sendgrid-java +``` + +### Environment Variables + +First, get your free Twilio SendGrid account [here](https://sendgrid.com/free?source=sendgrid-java). + +Next, update your environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys). + +```bash +echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env +echo "sendgrid.env" >> .gitignore +source ./sendgrid.env +./gradlew build +``` + +##### Execute: ##### + +See the [examples folder](examples) to get started quickly. + +Check out the documentation for [Web API v3 endpoints](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html). + +```bash +./gradlew build +cd examples +touch Example.java +``` + +Add the example you want to test to Example.java, including the headers at the top of the file. + +``` bash +javac -classpath ../repo/com/sendgrid/4.10.3/sendgrid-4.10.3-jar.jar:. Example.java && java -classpath ../repo/com/sendgrid/4.10.3/sendgrid-4.10.3-jar.jar:. Example +``` + + +## Understanding the Code Base + +**/examples** + +Working examples that demonstrate usage. + +**/src/test** + +Unit and integration tests. + +**/src/main** + +The interface to the Twilio SendGrid API. + + +## Testing + +All PRs require passing tests before the PR will be reviewed. + +All test files are in the [`tests`](src/test/java/com/sendgrid) directory. + +For the purposes of contributing to this repo, please update the [`SendGridTest.java`](src/test/java/com/sendgrid/SendGridTest.java) file with unit tests as you modify the code. + +The integration tests require a Twilio SendGrid mock API in order to execute. We've simplified setting this up using Docker to run the tests. You will just need [Docker Desktop](https://docs.docker.com/get-docker/) and `make`. + +Once these are available, simply execute the Docker test target to run all tests: `make test-docker`. This command can also be used to open an interactive shell into the container where this library is installed. To start a *bash* shell for example, use this command: `command=bash make test-docker`. + + +## Style Guidelines & Naming Conventions + +Generally, we follow the style guidelines as suggested by the official language. However, we ask that you conform to the styles that already exist in the library. If you wish to deviate, please explain your reasoning. + +Please run your code through: +- [FindBugs](http://findbugs.sourceforge.net/) +- [CheckStyle](http://checkstyle.sourceforge.net/) with [Google's Java Style Guide](https://google.github.io/styleguide/javaguide.html). + + +## Creating a Pull Request + + +1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork, + and configure the remotes: + + ```bash + # Clone your fork of the repo into the current directory + git clone https://github.com/sendgrid/sendgrid-java + + # Navigate to the newly cloned directory + cd sendgrid-java + + # Assign the original repo to a remote called "upstream" + git remote add upstream https://github.com/sendgrid/sendgrid-java + ``` + +2. If you cloned a while ago, get the latest changes from upstream: + + ```bash + git checkout + git pull upstream + ``` + +3. Create a new topic branch (off the main project development branch) to + contain your feature, change, or fix: + + ```bash + git checkout -b development + ``` + +4. Commit your changes in logical chunks. Please adhere to these [git commit + message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) + or your code is unlikely be merged into the main project. Use Git's + [interactive rebase](https://help.github.com/articles/interactive-rebase) + feature to tidy up your commits before making them public. + +4a. Create tests. + +4b. Create or update the example code that demonstrates the functionality of this change to the code. + +5. Locally merge (or rebase) the upstream `development` branch into your topic branch: + + ```bash + git pull [--rebase] upstream development + ``` + +6. Push your topic branch up to your fork: + + ```bash + git push origin + ``` + +7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) + with a clear title and description against the `main` branch. All tests must be passing before we will review the PR. + +## Code Reviews +If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, GitHub has some great information on how to review a Pull Request. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..6587fff8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +ARG version=latest +FROM openjdk:$version + +# version <= 11 +RUN apt-get update \ + && apt-get install -y make maven || true +COPY prism/prism/nginx/cert.crt /usr/local/share/ca-certificates/cert.crt +RUN update-ca-certificates || true + +# version > 11 +RUN yum update -y \ + && yum install -y make wget || true +RUN wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo \ + && yum install -y maven || true +RUN keytool -import -trustcacerts -cacerts -storepass changeit -noprompt \ + -alias api.sendgrid.com -file /usr/local/share/ca-certificates/cert.crt || true + +WORKDIR /app +COPY . . + +RUN make install diff --git a/FIRST_TIMERS.md b/FIRST_TIMERS.md new file mode 100644 index 00000000..667746df --- /dev/null +++ b/FIRST_TIMERS.md @@ -0,0 +1,53 @@ +# How To Contribute to Twilio SendGrid Repositories via GitHub +Contributing to the Twilio SendGrid repositories is easy! All you need to do is find an open issue (see the bottom of this page for a list of repositories containing open issues), fix it and submit a pull request. Once you have submitted your pull request, the team can easily review it before it is merged into the repository. + +To make a pull request, follow these steps: + +1. Log into GitHub. If you do not already have a GitHub account, you will have to create one in order to submit a change. Click the Sign up link in the upper right-hand corner to create an account. Enter your username, password, and email address. If you are an employee of Twilio SendGrid, please use your full name with your GitHub account and enter Twilio SendGrid as your company so we can easily identify you. + + + +2. __[Fork](https://help.github.com/fork-a-repo/)__ the [sendgrid-java](https://github.com/sendgrid/sendgrid-java) repository: + + + +3. __Clone__ your fork via the following commands: + +```bash +# Clone your fork of the repo into the current directory +git clone https://github.com/your_username/sendgrid-java +# Navigate to the newly cloned directory +cd sendgrid-java +# Assign the original repo to a remote called "upstream" +git remote add upstream https://github.com/sendgrid/sendgrid-java +``` + +> Don't forget to replace *your_username* in the URL by your real GitHub username. + +4. __Create a new topic branch__ (off the main project development branch) to contain your feature, change, or fix: + +```bash +git checkout -b +``` + +5. __Commit your changes__ in logical chunks. + +Please adhere to these [git commit message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) or your code is unlikely be merged into the main project. Use Git's [interactive rebase](https://help.github.com/articles/interactive-rebase) feature to tidy up your commits before making them public. Probably you will also have to create tests (if needed) or create or update the example code that demonstrates the functionality of this change to the code. + +6. __Locally merge (or rebase)__ the upstream development branch into your topic branch: + +```bash +git pull [--rebase] upstream main +``` + +7. __Push__ your topic branch up to your fork: + +```bash +git push origin +``` + +8. __[Open a Pull Request](https://help.github.com/articles/creating-a-pull-request/#changing-the-branch-range-and-destination-repository/)__ with a clear title and description against the `main` branch. All tests must be passing before we will review the PR. + +## Important notice + +Before creating a pull request, make sure that you respect the repository's constraints regarding contributions. You can find them in the [CONTRIBUTING.md](CONTRIBUTING.md) file. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..126ceb1a --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2025, Twilio SendGrid, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..3983b6aa --- /dev/null +++ b/Makefile @@ -0,0 +1,27 @@ +.PHONY: install package test test-integ test-docker update-deps clean + +VERSION := $(shell mvn help:evaluate -Dexpression=project.version --batch-mode | grep -e '^[^\[]') +install: + @java -version || (echo "Java is not installed, please install Java >= 7"; exit 1); + mvn clean install -DskipTests=true -Dgpg.skip -Dmaven.javadoc.skip=true -B + cp target/sendgrid-java-$(VERSION)-shaded.jar sendgrid-java.jar + +package: + mvn package -DskipTests=true -Dgpg.skip -Dmaven.javadoc.skip=true -B + cp target/sendgrid-java-$(VERSION)-shaded.jar sendgrid-java.jar + +test: + mvn test spotbugs:spotbugs checkstyle:check -Dcheckstyle.config.location=google_checks.xml + +test-integ: test + +version ?= latest +test-docker: + curl -s https://raw.githubusercontent.com/sendgrid/sendgrid-oai/HEAD/prism/prism-java.sh -o prism.sh + version=$(version) bash ./prism.sh + +update-deps: + mvn versions:use-latest-releases versions:commit -DallowMajorUpdates=false + +clean: + mvn clean diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..c15ea433 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +# Fixes # + +A short description of what this PR does. + +### Checklist +- [x] I acknowledge that all my contributions will be made under the project's license +- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar) +- [ ] I have read the [Contribution Guidelines](https://github.com/sendgrid/sendgrid-java/blob/main/CONTRIBUTING.md) and my PR follows them +- [ ] I have titled the PR appropriately +- [ ] I have updated my branch with the main branch +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have added the necessary documentation about the functionality in the appropriate .md file +- [ ] I have added inline documentation to the code I modified + +If you have questions, please file a [support ticket](https://support.sendgrid.com). diff --git a/README.md b/README.md index d20fd959..090a0536 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,56 @@ -# SendGrid-Java +![SendGrid Logo](twilio_sendgrid_logo.png) -This Java module allows you to quickly and easily send emails through SendGrid using Java. +[![BuildStatus](https://github.com/sendgrid/sendgrid-java/actions/workflows/test-and-deploy.yml/badge.svg)](https://github.com/sendgrid/sendgrid-java/actions/workflows/test-and-deploy.yml) +[![Maven Central](https://img.shields.io/maven-central/v/com.sendgrid/sendgrid-java.svg)](http://mvnrepository.com/artifact/com.sendgrid/sendgrid-java) +[![Twitter Follow](https://img.shields.io/twitter/follow/sendgrid.svg?style=social&label=Follow)](https://twitter.com/sendgrid) +[![GitHub contributors](https://img.shields.io/github/contributors/sendgrid/sendgrid-java.svg)](https://github.com/sendgrid/sendgrid-java/graphs/contributors) +[![Open Source Helpers](https://www.codetriage.com/sendgrid/sendgrid-java/badges/users.svg)](https://www.codetriage.com/sendgrid/sendgrid-java) +[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -[![BuildStatus](https://travis-ci.org/sendgrid/sendgrid-java.svg?branch=master)](https://travis-ci.org/sendgrid/sendgrid-java) -[![BuildStatus](https://maven-badges.herokuapp.com/maven-central/com.sendgrid/sendgrid-java/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.sendgrid/sendgrid-java) +**This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via Java.** -### Warning +Version 3.X.X of this library provides full support for all Twilio SendGrid [Web API v3](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html) endpoints, including the new [v3 /mail/send](https://sendgrid.com/blog/introducing-v3mailsend-sendgrids-new-mail-endpoint). -Version ``2.x.x``, behaves differently in the ``addTo`` method. In the past this method defaulted to using the ``SMTPAPI`` header. Now you must explicitly call the ``addSmtpApiTo`` method. More on the ``SMTPAPI`` section. +This library represents the beginning of a new path for Twilio SendGrid. We want this library to be community driven and Twilio SendGrid led. We need your help to realize this goal. To help make sure we are building the right things in the right order, we ask that you create [issues](https://github.com/sendgrid/sendgrid-java/issues) and [pull requests](CONTRIBUTING.md) or simply upvote or comment on existing issues or pull requests. -```java -// SendGridExample.java -import com.sendgrid.*; +**If you need help using SendGrid, please check the [Twilio SendGrid Support Help Center](https://support.sendgrid.com).** -public class SendGridExample { - public static void main(String[] args) { - SendGrid sendgrid = new SendGrid("SENDGRID USERNAME", "SENDGRID_PASSWORD"); +# Table of Contents - SendGrid.Email email = new SendGrid.Email(); - email.addTo("example@example.com"); - email.setFrom("other@example.com"); - email.setSubject("Hello World"); - email.setText("My first email with SendGrid Java!"); +* [Installation](#installation) +* [Quick Start](#quick-start) +* [Usage](#usage) +* [Use Cases](#use-cases) +* [Announcements](#announcements) +* [How to Contribute](#contribute) +* [Troubleshooting](#troubleshooting) +* [About](#about) +* [Support](#support) +* [License](#license) - try { - SendGrid.Response response = sendgrid.send(email); - System.out.println(response.getMessage()); - } - catch (SendGridException e) { - System.err.println(e); - } - } -} -``` -Compile and run this example with + +# Installation + +## Prerequisites + +- Java 8 or 11 +- The Twilio SendGrid service, starting at the [free level](https://sendgrid.com/free?source=sendgrid-java) to send up to 40,000 emails for the first 30 days, then send 100 emails/day free forever or check out [our pricing](https://sendgrid.com/pricing?source=sendgrid-java). + +## Setup Environment Variables +Update the development environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys), for example: + +1. Copy the sample environment file to a new file +```bash +cp .env_sample .env +``` +2. Edit the new `.env` to add your API key +3. Source the `.env` file to set the variable in the current session ```bash -$ javac -classpath sendgrid-2.2.1-jar.jar:. SendGridExample.java && java -classpath sendgrid-2.2.1-jar.jar:. SendGridExample +source .env ``` -## Installation +## Install Package Choose your installation method - Maven w/ Gradle (recommended), Maven or Jar file. @@ -51,7 +62,7 @@ Add the following to your build.gradle file in the root of your project. ... dependencies { ... - compile 'com.sendgrid:sendgrid-java:2.2.1' + implementation 'com.sendgrid:sendgrid-java:4.10.3' } repositories { @@ -60,12 +71,6 @@ repositories { ... ``` -Then import the library - in the file appropriate to your Java project. - -```java -import com.sendgrid.SendGrid; -``` - ### via Maven ``` @@ -76,323 +81,149 @@ mvn install You can just drop the jar file in. It's a fat jar - it has all the dependencies built in. -[sendgrid-java.jar](https://sendgrid-open-source.s3.amazonaws.com/sendgrid-java/sendgrid-java.jar) - -```java -import com.sendgrid.*; -``` - -## Usage - -To begin using this library, initialize the SendGrid object with your SendGrid credentials OR a SendGrid API Key. API Key is the preferred method. API Keys are in beta. To configure API keys, visit https://sendgrid.com/beta/settings/api_keys. - -```java -import com.sendgrid.SendGrid; -SendGrid sendgrid = new SendGrid("sendgrid_username", "sendgrid_password"); -// or -SendGrid sendgrid = new SendGrid("sendgrid_api_key"); -``` - -Add your message details. - -```java -Email email = new Email(); -email.addTo("example@example.com"); -email.addToName("Example Guy"); -email.setFrom("other@example.com"); -email.setSubject("Hello World"); -email.setText("My first email through SendGrid"); -``` - -Send it. - -```java -sendgrid.send(email); -``` - -### To - -#### addTo - -```java -email.addTo("foo@example.com"); -// or -email.addTo(new String[]{"foo@other.com", "bar@other.com"}); -// or -email.addTo("foo.bar@other.com", "Foo Bar"); -``` - -#### setTo +[sendgrid-java.jar](https://github.com/sendgrid/sendgrid-java/releases/download/4.10.3/sendgrid-java.jar) -```java -email.setTo(new String[]{"foo@other.com", "bar@other.com"}); -``` +## Dependencies -#### addToName +- [Java-HTTP-Client](https://github.com/sendgrid/java-http-client) -```java -email.addToName("Foo"); -// or -email.addToName(new String[]{"Foo", "Bar"}); -``` + +# Quick Start -#### setToName +## Hello Email -```java -email.setToName(new String[]{"Foo", "Bar"}); -``` +The following is the minimum needed code to send an email with the [/mail/send Helper](src/main/java/com/sendgrid/helpers) ([here](examples/helpers/mail/Example.java#L30) is a full example): -#### addCc +### With Mail Helper Class ```java -email.addCc("foo@example.com"); -// or -email.addCc(new String[]{"foo@other.com", "bar@other.com"}); -``` - -#### setCc - -```java -email.setCc(new String[]{"foo@other.com", "bar@other.com"}); -``` - -#### addBcc - -```java -email.addBcc("foo@example.com"); -// or -email.addBcc(new String[]{"foo@other.com", "bar@other.com"}); -``` - -#### setBcc - -```java -email.setBcc(new String[]{"foo@other.com", "bar@other.com"}); -``` - -### From - -#### setFrom - -```java -email.setFrom("other@example.com"); -``` - -#### setFromName - -```java -email.setFromName("Other Dude"); -``` - -#### setReplyTo - -```java -email.setReplyTo("no-reply@nowhere.com"); -``` - -#### setSubject - -```java -email.setSubject("Hello World"); -``` - -#### setText - -```java -email.setText("This is some text of the email."); -``` - -#### setHtml - -```java -email.setHtml("

My first email through SendGrid"); -``` - -### Attachments - -#### addAttachment - -```java -email.addAttachment("text.txt", "contents"); -// or -email.addAttachment("image.png", new File("./image.png")); -// or -email.addAttachment("text.txt", new InputStream(new File("./file.txt"))); -``` - -### Content IDs - -#### addContentId - -```java -// First, add an attachment -email.addAttachment("image.png", new File("./image.png")); -// Map the name of the attachment to an ID -email.addContentId("image.png", "ID_IN_HTML") -// Map the ID in the HTML -email.setHtml("TEXT BEFORE IMAGEAFTER IMAGE") -``` - -### Proxy Server Setup - -```java -SendGrid sendgrid = new SendGrid("SENDGRID USERNAME", "SENDGRID_PASSWORD"); -HttpHost proxy = new HttpHost("server", 3128); -CloseableHttpClient http = HttpClientBuilder.create().setProxy(proxy).setUserAgent("sendgrid/" + sendgrid.getVersion() + ";java").build(); -sendgrid.setClient(http); -``` - -## [X-SMTPAPI](http://sendgrid.com/docs/API_Reference/SMTP_API/index.html) - -The mail object extends the SMTPAPI object which is found in [SMTPAPI-Java](https://github.com/sendgrid/smtpapi-java). - -```java -email.getSMTPAPI(); -``` - -### Recipients - -#### addSmtpApiTo - -```java -email.addSmtpApiTo("foo@example.com"); -// or -email.addSmtpApiTo(new String[]{"foo@other.com", "bar@other.com"}); -``` - -### [Substitutions](http://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html) - -#### addSubstitution - -```java -email.addSubstitution("key", "value"); - -JSONObject subs = header.getSubstitutions(); -``` - -#### setSubstitutions - -```java -email.setSubstitutions("key", new String[]{"value1", "value2"}); - -JSONObject subs = header.getSubstitutions(); -``` - -### [Unique Arguments](http://sendgrid.com/docs/API_Reference/SMTP_API/unique_arguments.html) - -#### addUniqueAarg - -```java -email.addUniqueAarg("key", "value"); -// or -Map map = new HashMap(); -map.put("unique", "value"); -email.setUniqueArgs(map); -// or -JSONObject map = new JSONObject(); -map.put("unique", "value"); -email.setUniqueArgs(map); -// or -email.setUniqueArgs(map); - -JSONObject args = email.getUniqueArgs(); +import com.sendgrid.*; +import java.io.IOException; + +public class Example { + public static void main(String[] args) throws IOException { + Email from = new Email("test@example.com"); + String subject = "Sending with Twilio SendGrid is Fun"; + Email to = new Email("test@example.com"); + Content content = new Content("text/plain", "and easy to do anywhere, even with Java"); + Mail mail = new Mail(from, subject, to, content); + + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + try { + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} ``` -### [Categories](http://sendgrid.com/docs/API_Reference/SMTP_API/categories.html) - -#### addCategory - -```java -email.addCategory("category"); - -String[] cats = email.getCategories(); -``` +The `Mail` constructor creates a [personalization object](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html) for you. [Here](examples/helpers/mail/Example.java#L221) is an example of how to add to it. -### [Sections](http://sendgrid.com/docs/API_Reference/SMTP_API/section_tags.html) +### Without Mail Helper Class -#### addSection +The following is the minimum needed code to send an email without the /mail/send Helper ([here](examples/mail/mail.java#L54) is a full example): ```java -email.addSection("key", "section"); +import com.sendgrid.*; +import java.io.IOException; -JSONObject sections = email.getSections(); +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Sending with Twilio SendGrid is Fun\"}],\"from\":{\"email\":\"test@example.com\"},\"content\":[{\"type\":\"text/plain\",\"value\": \"and easy to do anywhere, even with Java\"}]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} ``` -### [Filters / Apps](http://sendgrid.com/docs/API_Reference/SMTP_API/apps.html) - -You can enable and configure Apps. - -#### addFilter +## General v3 Web API Usage ```java -email.addFilter("filter", "setting", "value"); -email.addFilter("filter", "setting", 1); - -JSONObject filters = email.getFilters(); -``` - -Example enabling bcc app: +import com.sendgrid.*; +import java.io.IOException; -```java -SendGrid sendgrid = new SendGrid("sendgrid_username", "sendgrid_password"); -sendgrid.addTo("example@example.com"); -... -sendgrid.addFilter("bcc", "enabled", 1); -sendgrid.addFilter("bcc", "email", "example@example.com"); +public class Example { + public static void main(String[] args) throws IOException { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} ``` -### [ASM - Advanced Supression Manager](https://sendgrid.com/docs/User_Guide/advanced_suppression_manager.html) - -#### setASMGroupId - -```java -email.setASMGroupId(1); -``` + +# Usage -### [Schedule Sending](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) +- [Twilio SendGrid Docs](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html) +- [Library Usage Docs](USAGE.md) +- [Example Code](examples) +- [How-to: Migration from v2 to v3](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/how_to_migrate_from_v2_to_v3_mail_send.html) +- [v3 Web API Mail Send Helper](src/main/java/com/sendgrid/helpers) - build a request object payload for a v3 /mail/send API call. -#### setSendAt -```java -email.setSendAt(1409348513); -``` + +# Use Cases -### [Templates](https://sendgrid.com/docs/API_Reference/Web_API_v3/Template_Engine/index.html) +[Examples of common API use cases](use-cases), such as how to send an email with a transactional template. -#### setTemplateId + +# Announcements -```java -email.setTemplateId("abc123-def456"); -``` +All updates to this library are documented in our [CHANGELOG](CHANGELOG.md) and [releases](https://github.com/sendgrid/sendgrid-java/releases). -## Contributing + +# How to Contribute -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Added some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request +We encourage contribution to our libraries (you might even score some nifty swag), please see our [CONTRIBUTING](CONTRIBUTING.md) guide for details. -## Running Tests +Quick links: -The existing tests in the `src/test` directory can be run using gradle with the following command: +- [Feature Request](CONTRIBUTING.md#feature-request) +- [Bug Reports](CONTRIBUTING.md#submit-a-bug-report) +- [Improvements to the Codebase](CONTRIBUTING.md#improvements-to-the-codebase) -```bash -$ ./gradlew test -i -``` + +# Troubleshooting -## Generating the jar +Please see our [troubleshooting guide](TROUBLESHOOTING.md) for common library issues. -```bash -$ ./gradlew build -``` + +# About -## Example App +sendgrid-java is maintained and funded by Twilio SendGrid, Inc. The names and logos for sendgrid-java are trademarks of Twilio SendGrid, Inc. -We have an example app using this library. This can be helpful to get a grasp on implementing it in your own app. + +# Support -[github.com/scottmotte/sendgrid-java-example](http://github.com/scottmotte/sendgrid-java-example) +If you need help installing or using the library, please check the [Twilio SendGrid Support Help Center](https://support.sendgrid.com). -## License +# License -Licensed under the MIT License. +[The MIT License (MIT)](LICENSE) diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md new file mode 100644 index 00000000..44b5c885 --- /dev/null +++ b/TROUBLESHOOTING.md @@ -0,0 +1,129 @@ +If you have an issue logging into your Twilio SendGrid account, please read this [document](https://sendgrid.com/docs/ui/account-and-settings/troubleshooting-login/). For any questions regarding login issues, please contact our [support team](https://support.sendgrid.com). + +If you have a non-library SendGrid issue, please contact our [support team](https://support.sendgrid.com). + +If you can't find a solution below, please open an [issue](https://github.com/sendgrid/sendgrid-java/issues). + + +## Table of Contents + +- [Table of Contents](#table-of-contents) +- [Migrating from v2 to v3](#migrating-from-v2-to-v3) +- [Continue Using v2](#continue-using-v2) + - [via Maven w/ Gradle](#via-maven-w-gradle) + - [via jar file](#via-jar-file) +- [Testing v3 /mail/send Calls Directly](#testing-v3-mailsend-calls-directly) +- [Versions](#versions) +- [Environment Variables and Your Twilio SendGrid API Key](#environment-variables-and-your-twilio-sendgrid-api-key) +- [Using the Package Manager](#using-the-package-manager) +- [Android Compatibility](#android-compatibility) +- [Viewing the Request Body](#viewing-the-request-body) +- [Verifying Event Webhooks](#signed-webhooks) + + +## Migrating from v2 to v3 + +Please review [our guide](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/how_to_migrate_from_v2_to_v3_mail_send.html) on how to migrate from v2 to v3. + + +## Continue Using v2 + +[Here](https://github.com/sendgrid/sendgrid-java/tree/b64988f85474e04e9d75e17860d64ffacda1cdff) is the last working version with v2 support. + +### via Maven w/ Gradle + +Add the following to your build.gradle file in the root of your project. + +```groovy +... +dependencies { + ... + compile 'com.sendgrid:sendgrid-java:2.2.2' +} + +repositories { + mavenCentral() +} +... +``` + +### via jar file + +You can just drop the jar file in. It's a fat jar - it has all the dependencies built in. + +[sendgrid-java.jar](http://repo1.maven.org/maven2/com/sendgrid/sendgrid-java/2.2.2/sendgrid-java-2.2.2-jar.jar) + + +## Testing v3 /mail/send Calls Directly + +[Here](https://sendgrid.com/docs/for-developers/sending-email/curl-examples/) are some cURL examples for common use cases. + + +## Versions + +We follow the MAJOR.MINOR.PATCH versioning scheme as described by [SemVer.org](http://semver.org). Therefore, we recommend that you always pin (or vendor) the particular version you are working with your code and never auto-update to the latest version. Especially when there is a MAJOR point release since that is guaranteed to be a breaking change. Changes are documented in the [CHANGELOG](CHANGELOG.md) and [releases](https://github.com/sendgrid/sendgrid-java/releases) section. + + +## Environment Variables and Your Twilio SendGrid API Key + +All of our examples assume you are using [environment variables](https://github.com/sendgrid/sendgrid-java#setup-environment-variables) to hold your Twilio SendGrid API key. + +If you choose to add your Twilio SendGrid API key directly (not recommended): + +`System.getenv("SENDGRID_API_KEY")` + +becomes + +`"SENDGRID_API_KEY"` + +In the first case, SENDGRID_API_KEY is in reference to the name of the environment variable, while the second case references the actual Twilio SendGrid API Key. + + +## Using the Package Manager + +We upload this library to [Maven](http://repo1.maven.org/maven2/com/sendgrid/sendgrid-java/) whenever we make a release. This allows you to use [maven and gradle](https://maven.apache.org/) for easy installation. + +In most cases we recommend you download the latest version of the library, but if you need a different version, please use: + +```groovy +... +dependencies { + ... + compile 'com.sendgrid:sendgrid-java:X.X.X' +} + +repositories { + mavenCentral() +} +... +``` + + +## Android Compatibility + +Since Android SDK 23, HttpClient is no longer supported. Some workarounds can be found [here](http://stackoverflow.com/questions/32153318/httpclient-wont-import-in-android-studio). + +We have an issue to remove that dependency [here](https://github.com/sendgrid/java-http-client/issues/2), please upvote to move it up the queue. + + +## Viewing the Request Body + +When debugging or testing, it may be useful to examine the raw request body to compare against the [documented format](https://sendgrid.com/docs/API_Reference/api_v3.html). + +You can do this right before you call `request.setBody(mail.build())` like so: + +```java +System.out.println(mail.build()); +``` + + +## Signed Webhook Verification + +Twilio SendGrid's Event Webhook will notify a URL via HTTP POST with information about events that occur as your mail is processed. [This](https://docs.sendgrid.com/for-developers/tracking-events/getting-started-event-webhook-security-features) article covers all you need to know to secure the Event Webhook, allowing you to verify that incoming requests originate from Twilio SendGrid. The sendgrid-java library can help you verify these Signed Event Webhooks. + +You can find the end-to-end usage example [here](examples/helpers/eventwebhook/Example.java) and the tests [here](/src/test/java/com/sendgrid/helpers/eventwebhook/EventWebhookTest.java). + +If you are still having trouble getting the validation to work, follow the following instructions: +- Be sure to use the *raw* payload for validation +- Be sure to include a trailing carriage return and newline in your payload +- In case of multi-event webhooks, make sure you include the trailing newline and carriage return after *each* event diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 00000000..e5b3e1d2 --- /dev/null +++ b/USAGE.md @@ -0,0 +1,6346 @@ +This documentation is based on our [OAI specification](https://github.com/sendgrid/sendgrid-oai). + +# INITIALIZATION + +```java +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +public class Example { + public static void main(String[] args) throws IOException { + // Add the example code here + } +} +``` + +# Table of Contents + +* [ACCESS SETTINGS](#access-settings) +* [ALERTS](#alerts) +* [API KEYS](#api-keys) +* [ASM](#asm) +* [BROWSERS](#browsers) +* [CAMPAIGNS](#campaigns) +* [CATEGORIES](#categories) +* [CLIENTS](#clients) +* [CONTACTDB](#contactdb) +* [DEVICES](#devices) +* [GEO](#geo) +* [IPS](#ips) +* [MAIL](#mail) +* [MAIL SETTINGS](#mail-settings) +* [MAILBOX PROVIDERS](#mailbox-providers) +* [PARTNER SETTINGS](#partner-settings) +* [SCOPES](#scopes) +* [SENDERS](#senders) +* [SENDER AUTHENTICATION](#sender-authentication) +* [STATS](#stats) +* [SUBUSERS](#subusers) +* [SUPPRESSION](#suppression) +* [TEMPLATES](#templates) +* [TRACKING SETTINGS](#tracking-settings) +* [USER](#user) + + + +# ACCESS SETTINGS + +## Retrieve all recent access attempts + +**This endpoint allows you to retrieve a list of all of the IP addresses that recently attempted to access your account either through the User Interface or the API.** + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### GET /access_settings/activity + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/activity"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add one or more IPs to the whitelist + +**This endpoint allows you to add one or more IP addresses to your IP whitelist.** + +When adding an IP to your whitelist, include the IP address in an array. You can whitelist one IP at a time, or you can whitelist multiple IPs at once. + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### POST /access_settings/whitelist + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("access_settings/whitelist"); + request.setBody("{\"ips\":[{\"ip\":\"192.168.1.1\"},{\"ip\":\"192.*.*.*\"},{\"ip\":\"192.168.1.3/32\"}]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a list of currently whitelisted IPs + +**This endpoint allows you to retrieve a list of IP addresses that are currently whitelisted.** + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### GET /access_settings/whitelist + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/whitelist"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Remove one or more IPs from the whitelist + +**This endpoint allows you to remove one or more IPs from your IP whitelist.** + +You can remove one IP at a time, or you can remove multiple IP addresses. + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### DELETE /access_settings/whitelist + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("access_settings/whitelist"); + request.setBody("{\"ids\":[1,2,3]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific whitelisted IP + +**This endpoint allows you to retrieve a specific IP address that has been whitelisted.** + +You must include the ID for the specific IP address you want to retrieve in your call. + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### GET /access_settings/whitelist/{rule_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/whitelist/{rule_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Remove a specific IP from the whitelist + +**This endpoint allows you to remove a specific IP address from your IP whitelist.** + +When removing a specific IP address from your whitelist, you must include the ID in your call. + +IP Access Management allows you to control which IP addresses can be used to access your account, either through the User Interface or the API. There is no limit to the number of IP addresses that you can add to your whitelist. It is possible to remove your own IP address from the whitelist, thus preventing yourself from accessing your account. + +For more information, please see our [User Guide](http://sendgrid.com/docs/User_Guide/Settings/ip_access_management.html). + +### DELETE /access_settings/whitelist/{rule_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("access_settings/whitelist/{rule_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# ALERTS + +## Create a new Alert + +**This endpoint allows you to create a new alert.** + +Alerts allow you to specify an email address to receive notifications regarding your email usage or statistics. +* Usage alerts allow you to set the threshold at which an alert will be sent. +* Stats notifications allow you to set how frequently you would like to receive email statistics reports. For example, "daily", "weekly", or "monthly". + +For more information about alerts, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/alerts.html). + +### POST /alerts + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("alerts"); + request.setBody("{\"type\":\"stats_notification\",\"frequency\":\"daily\",\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all alerts + +**This endpoint allows you to retrieve all of your alerts.** + +Alerts allow you to specify an email address to receive notifications regarding your email usage or statistics. +* Usage alerts allow you to set the threshold at which an alert will be sent. +* Stats notifications allow you to set how frequently you would like to receive email statistics reports. For example, "daily", "weekly", or "monthly". + +For more information about alerts, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/alerts.html). + +### GET /alerts + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update an alert + +**This endpoint allows you to update an alert.** + +Alerts allow you to specify an email address to receive notifications regarding your email usage or statistics. +* Usage alerts allow you to set the threshold at which an alert will be sent. +* Stats notifications allow you to set how frequently you would like to receive email statistics reports. For example, "daily", "weekly", or "monthly". + +For more information about alerts, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/alerts.html). + +### PATCH /alerts/{alert_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("alerts/{alert_id}"); + request.setBody("{\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific alert + +**This endpoint allows you to retrieve a specific alert.** + +Alerts allow you to specify an email address to receive notifications regarding your email usage or statistics. +* Usage alerts allow you to set the threshold at which an alert will be sent. +* Stats notifications allow you to set how frequently you would like to receive email statistics reports. For example, "daily", "weekly", or "monthly". + +For more information about alerts, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/alerts.html). + +### GET /alerts/{alert_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete an alert + +**This endpoint allows you to delete an alert.** + +Alerts allow you to specify an email address to receive notifications regarding your email usage or statistics. +* Usage alerts allow you to set the threshold at which an alert will be sent. +* Stats notifications allow you to set how frequently you would like to receive email statistics reports. For example, "daily", "weekly", or "monthly". + +For more information about alerts, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/alerts.html). + +### DELETE /alerts/{alert_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# API KEYS + +## Create API keys + +**This endpoint allows you to create a new random API Key for the user.** + +A JSON request body containing a "name" property is required. If the number of maximum keys is reached, HTTP 403 will be returned. + +There is a limit of 100 API Keys on your account. + +The API Keys feature allows customers to be able to generate an API Key credential which can be used for authentication with the SendGrid v3 Web API or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + +See the [API Key Permissions List](https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/api_key_permissions_list.html) for a list of all available scopes. + +### POST /api_keys + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("api_keys"); + request.setBody("{\"sample\":\"data\",\"scopes\":[\"mail.send\",\"alerts.create\",\"alerts.read\"],\"name\":\"My API Key\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all API Keys belonging to the authenticated user + +**This endpoint allows you to retrieve all API Keys that belong to the authenticated user.** + +The API Keys feature allows customers to be able to generate an API Key credential which can be used for authentication with the SendGrid v3 Web API or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + +### GET /api_keys + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update the name & scopes of an API Key + +**This endpoint allows you to update the name and scopes of a given API key.** + +A JSON request body with a "name" property is required. +Most provide the list of all the scopes an API key should have. + +The API Keys feature allows customers to be able to generate an API Key credential which can be used for authentication with the SendGrid v3 Web API or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + + +### PUT /api_keys/{api_key_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"scopes\":[\"user.profile.read\",\"user.profile.update\"],\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update API keys + +**This endpoint allows you to update the name of an existing API Key.** + +A JSON request body with a "name" property is required. + +The API Keys feature allows customers to be able to generate an API Key credential which can be used for authentication with the Twilio SendGrid v3 Web API or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + +## URI Parameters + +| URI Parameter | Type | Required? | Description | +|---|---|---|---| +|api_key_id |string | required | The ID of the API Key you are updating.| + +### PATCH /api_keys/{api_key_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve an existing API Key + +**This endpoint allows you to retrieve a single API key.** + +If the API Key ID does not exist an HTTP 404 will be returned. + +### GET /api_keys/{api_key_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete API keys + +**This endpoint allows you to revoke an existing API Key.** + +Authentications using this API Key will fail after this request is made, with some small propagation delay. If the API Key ID does not exist an HTTP 404 will be returned. + +The API Keys feature allows customers to be able to generate an API Key credential which can be used for authentication with the Twilio SendGrid v3 Web API or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + +## URI Parameters + +| URI Parameter | Type | Required? | Description | +|---|---|---|---| +|api_key_id |string | required | The ID of the API Key you are deleting.| + +### DELETE /api_keys/{api_key_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# ASM + +## Create a new suppression group + +**This endpoint allows you to create a new suppression group.** + +Suppression groups, or unsubscribe groups, are specific types or categories of email that you would like your recipients to be able to unsubscribe from. For example: Daily Newsletters, Invoices, System Alerts. + +The **name** and **description** of the unsubscribe group will be visible to recipients when they are managing their subscriptions. + +Each user can create up to 25 different suppression groups. + +### POST /asm/groups + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups"); + request.setBody("{\"is_default\":true,\"description\":\"Suggestions for products our users might like.\",\"name\":\"Product) Suggestions\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve information about multiple suppression groups + +**This endpoint allows you to retrieve information about multiple suppression groups.** + +This endpoint will return information for each group ID that you include in your request. To add a group ID to your request, simply append `&id=` followed by the group ID. + +Suppressions are a list of email addresses that will not receive content sent under a given [group](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). + +Suppression groups, or [unsubscribe groups](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html), allow you to label a category of content that you regularly send. This gives your recipients the ability to opt out of a specific set of your email. For example, you might define a group for your transactional email, and one for your marketing email so that your users can continue receiving your transactional email without having to receive your marketing content. + +### GET /asm/groups + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups"); + request.addQueryParam("id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a suppression group. + +**This endpoint allows you to update or change a suppression group.** + +Suppression groups, or unsubscribe groups, are specific types or categories of email that you would like your recipients to be able to unsubscribe from. For example: Daily Newsletters, Invoices, System Alerts. + +The **name** and **description** of the unsubscribe group will be visible to recipients when they are managing their subscriptions. + +Each user can create up to 25 different suppression groups. + +### PATCH /asm/groups/{group_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("asm/groups/{group_id}"); + request.setBody("{\"description\":\"Suggestions for items our users might like.\",\"name\":\"Item Suggestions\",\"id\":103}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Get information on a single suppression group. + +**This endpoint allows you to retrieve a single suppression group.** + +Suppression groups, or unsubscribe groups, are specific types or categories of email that you would like your recipients to be able to unsubscribe from. For example: Daily Newsletters, Invoices, System Alerts. + +The **name** and **description** of the unsubscribe group will be visible to recipients when they are managing their subscriptions. + +Each user can create up to 25 different suppression groups. + +### GET /asm/groups/{group_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a suppression group. + +**This endpoint allows you to delete a suppression group.** + +You can only delete groups that have not been attached to sent mail in the last 60 days. If a recipient uses the "one-click unsubscribe" option on an email associated with a deleted group, that recipient will be added to the global suppression list. + +Suppression groups, or unsubscribe groups, are specific types or categories of email that you would like your recipients to be able to unsubscribe from. For example: Daily Newsletters, Invoices, System Alerts. + +The **name** and **description** of the unsubscribe group will be visible to recipients when they are managing their subscriptions. + +Each user can create up to 25 different suppression groups. + +### DELETE /asm/groups/{group_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add suppressions to a suppression group + +**This endpoint allows you to add email addresses to an unsubscribe group.** + +If you attempt to add suppressions to a group that has been deleted or does not exist, the suppressions will be added to the global suppressions list. + +Suppressions are recipient email addresses that are added to [unsubscribe groups](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). Once a recipient's address is on the suppressions list for an unsubscribe group, they will not receive any emails that are tagged with that unsubscribe group. + +### POST /asm/groups/{group_id}/suppressions + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all suppressions for a suppression group + +**This endpoint allows you to retrieve all suppressed email addresses belonging to the given group.** + +Suppressions are recipient email addresses that are added to [unsubscribe groups](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). Once a recipient's address is on the suppressions list for an unsubscribe group, they will not receive any emails that are tagged with that unsubscribe group. + +### GET /asm/groups/{group_id}/suppressions + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Search for suppressions within a group + +**This endpoint allows you to search a suppression group for multiple suppressions.** + +When given a list of email addresses and a group ID, this endpoint will return only the email addresses that have been unsubscribed from the given group. + +Suppressions are a list of email addresses that will not receive content sent under a given [group](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). + +### POST /asm/groups/{group_id}/suppressions/search + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions/search"); + request.setBody("{\"recipient_emails\":[\"exists1@example.com\",\"exists2@example.com\",\"doesnotexists@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a suppression from a suppression group + +**This endpoint allows you to remove a suppressed email address from the given suppression group.** + +Suppressions are recipient email addresses that are added to [unsubscribe groups](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). Once a recipient's address is on the suppressions list for an unsubscribe group, they will not receive any emails that are tagged with that unsubscribe group. + +### DELETE /asm/groups/{group_id}/suppressions/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}/suppressions/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all suppressions + +**This endpoint allows you to retrieve a list of all suppressions.** + +Suppressions are a list of email addresses that will not receive content sent under a given [group](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). + +### GET /asm/suppressions + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add recipient addresses to the global suppression group. + +**This endpoint allows you to add one or more email addresses to the global suppressions group.** + +A global suppression (or global unsubscribe) is an email address of a recipient who does not want to receive any of your messages. A globally suppressed recipient will be removed from any email you send. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/global_unsubscribes.html). + +### POST /asm/suppressions/global + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/suppressions/global"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a Global Suppression + +**This endpoint allows you to retrieve a global suppression. You can also use this endpoint to confirm if an email address is already globally suppressed.** + +If the email address you include in the URL path parameter `{email}` is already globally suppressed, the response will include that email address. If the address you enter for `{email}` is not globally suppressed, an empty JSON object `{}` will be returned. + +A global suppression (or global unsubscribe) is an email address of a recipient who does not want to receive any of your messages. A globally suppressed recipient will be removed from any email you send. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/global_unsubscribes.html). + +### GET /asm/suppressions/global/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Global Suppression + +**This endpoint allows you to remove an email address from the global suppressions group.** + +A global suppression (or global unsubscribe) is an email address of a recipient who does not want to receive any of your messages. A globally suppressed recipient will be removed from any email you send. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/global_unsubscribes.html). + +### DELETE /asm/suppressions/global/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all suppression groups for an email address + +**This endpoint returns the list of all groups that the given email address has been unsubscribed from.** + +Suppressions are a list of email addresses that will not receive content sent under a given [group](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html). + +### GET /asm/suppressions/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# BROWSERS + +## Retrieve email statistics by browser. + +**This endpoint allows you to retrieve your email statistics segmented by browser type.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /browsers/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("browsers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("browsers", "test_string"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("offset", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# CAMPAIGNS + +## Create a Campaign + +**This endpoint allows you to create a campaign.** + +Our Marketing Campaigns API lets you create, manage, send, and schedule campaigns. + +Note: In order to send or schedule the campaign, you will be required to provide a subject, sender ID, content (we suggest both HTML and plain text), and at least one list or segment ID. This information is not required when you create a campaign. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### POST /campaigns + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns"); + request.setBody("{\"custom_unsubscribe_url\":\"\",\"html_content\":\"

Check out our) spring line!

\",\"list_ids\":[110,124],\"sender_id\":124451,\"subject\":\"New Products for Spring!\",\"plain_content\":\"Check out our spring line!\",\"suppression_group_id\":42,\"title\":\"March Newsletter\",\"segment_ids\":[110],\"categories\":[\"spring line\"],\"ip_pool\":\"marketing\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all Campaigns + +**This endpoint allows you to retrieve a list of all of your campaigns.** + +Returns campaigns in reverse order they were created (newest first). + +Returns an empty array if no campaigns exist. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### GET /campaigns + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a Campaign + +Update a campaign. This is especially useful if you only set up the campaign using POST /campaigns, but didn't set many of the parameters. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### PATCH /campaigns/{campaign_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}"); + request.setBody("{\"html_content\":\"

Check out our summer line!

\",\"subject\":\"New Products for Summer!\",\"title\":\"May Newsletter\",\"categories\":[\"summer line\"],\"plain_content\":\"Check out our summer line!\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a single campaign + +**This endpoint allows you to retrieve a specific campaign.** + +Our Marketing Campaigns API lets you create, manage, send, and schedule campaigns. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### GET /campaigns/{campaign_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Campaign + +**This endpoint allows you to delete a specific campaign.** + +Our Marketing Campaigns API lets you create, manage, send, and schedule campaigns. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### DELETE /campaigns/{campaign_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a Scheduled Campaign + +**This endpoint allows to you change the scheduled time and date for a campaign to be sent.** + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### PATCH /campaigns/{campaign_id}/schedules + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489451436}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Schedule a Campaign + +**This endpoint allows you to schedule a specific date and time for your campaign to be sent.** + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### POST /campaigns/{campaign_id}/schedules + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489771528}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## View Scheduled Time of a Campaign + +**This endpoint allows you to retrieve the date and time that the given campaign has been scheduled to be sent.** + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### GET /campaigns/{campaign_id}/schedules + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Unschedule a Scheduled Campaign + +**This endpoint allows you to unschedule a campaign that has already been scheduled to be sent.** + +A successful unschedule will return a 204. +If the specified campaign is in the process of being sent, the only option is to cancel (a different method). + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### DELETE /campaigns/{campaign_id}/schedules + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Send a Campaign + +**This endpoint allows you to immediately send a campaign at the time you make the API call.** + +Normally a POST would have a request body, but since this endpoint is telling us to send a resource that is already created, a request body is not needed. + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### POST /campaigns/{campaign_id}/schedules/now + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/now"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Send a Test Campaign + +**This endpoint allows you to send a test campaign.** + +To send to multiple addresses, use an array for the JSON "to" value ["one@address","two@address"] + +For more information: + +* [User Guide > Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) + +### POST /campaigns/{campaign_id}/schedules/test + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/test"); + request.setBody("{\"to\":\"your.email@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# CATEGORIES + +## Retrieve all categories + +**This endpoint allows you to retrieve a list of all of your categories.** + +Categories can help organize your email analytics by enabling you to tag emails by type or broad topic. You can define your own custom categories. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/categories.html). + +### GET /categories + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories"); + request.addQueryParam("category", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Email Statistics for Categories + +**This endpoint allows you to retrieve all of your email statistics for each of your categories.** + +If you do not define any query parameters, this endpoint will return a sum for each category in groups of 10. + +Categories allow you to group your emails together according to broad topics that you define. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/categories.html). + +### GET /categories/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("categories", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve sums of email stats for each category [Needs: Stats object defined, has category ID?] + +**This endpoint allows you to retrieve the total sum of each email statistic for every category over the given date range.** + +If you do not define any query parameters, this endpoint will return a sum for each category in groups of 10. + +Categories allow you to group your emails together according to broad topics that you define. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/categories.html). + +### GET /categories/stats/sums + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# CLIENTS + +## Retrieve email statistics by client type. + +**This endpoint allows you to retrieve your email statistics segmented by client type.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /clients/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve stats by a specific client type. + +**This endpoint allows you to retrieve your email statistics segmented by a specific client type.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +## Available Client Types +- phone +- tablet +- webmail +- desktop + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /clients/{client_type}/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/{client_type}/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# CONTACTDB + +## Create a Custom Field + +**This endpoint allows you to create a custom field.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### POST /contactdb/custom_fields + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/custom_fields"); + request.setBody("{\"type\":\"text\",\"name\":\"pet\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all custom fields + +**This endpoint allows you to retrieve all custom fields.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### GET /contactdb/custom_fields + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a Custom Field + +**This endpoint allows you to retrieve a custom field by ID.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### GET /contactdb/custom_fields/{custom_field_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Custom Field + +**This endpoint allows you to delete a custom field by ID.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### DELETE /contactdb/custom_fields/{custom_field_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create a List + +**This endpoint allows you to create a list for your recipients.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### POST /contactdb/lists + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists"); + request.setBody("{\"name\":\"your list name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all lists + +**This endpoint allows you to retrieve all of your recipient lists. If you don't have any lists, an empty array will be returned.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/lists + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete Multiple lists + +**This endpoint allows you to delete multiple recipient lists.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### DELETE /contactdb/lists + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists"); + request.setBody("[1,2,3,4]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a List + +**This endpoint allows you to update the name of one of your recipient lists.** + + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### PATCH /contactdb/lists/{list_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/lists/{list_id}"); + request.setBody("{\"name\":\"newlistname\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a single list + +This endpoint allows you to retrieve a single recipient list. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/lists/{list_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a List + +**This endpoint allows you to delete a specific recipient list with the given ID.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### DELETE /contactdb/lists/{list_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add Multiple Recipients to a List + +**This endpoint allows you to add multiple recipients to a list.** + +Adds existing recipients to a list, passing in the recipient IDs to add. Recipient IDs should be passed exactly as they are returned from recipient endpoints. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### POST /contactdb/lists/{list_id}/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all recipients on a List + +**This endpoint allows you to retrieve all recipients on the list with the given ID.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/lists/{list_id}/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add a Single Recipient to a List + +**This endpoint allows you to add a single recipient to a list.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### POST /contactdb/lists/{list_id}/recipients/{recipient_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Single Recipient from a Single List + +**This endpoint allows you to delete a single recipient from a list.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### DELETE /contactdb/lists/{list_id}/recipients/{recipient_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + request.addQueryParam("recipient_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Recipient + +**This endpoint allows you to update one or more recipients.** + +The body of an API call to this endpoint must include an array of one or more recipient objects. + +It is of note that you can add custom field data as parameters on recipient objects. We have provided an example using some of the default custom fields Twilio SendGrid provides. + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### PATCH /contactdb/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"first_name\":\"Guy\",\"last_name\":\"Jones\",\"email\":\"jones@example.com\"}]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add recipients + +**This endpoint allows you to add a Marketing Campaigns recipient.** + +It is of note that you can add custom field data as a parameter on this endpoint. We have provided an example using some of the default custom fields Twilio SendGrid provides. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### POST /contactdb/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"age\":25,\"last_name\":\"User\",\"email\":\"example@example.com\",\"first_name\":\"\"},{\"age\":25,\"last)_name\":\"User\",\"email\":\"example2@example.com\",\"first_name\":\"Example\"}]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve recipients + +**This endpoint allows you to retrieve all of your Marketing Campaigns recipients.** + +Batch deletion of a page makes it possible to receive an empty page of recipients before reaching the end of +the list of recipients. To avoid this issue; iterate over pages until a 404 is retrieved. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete Recipient + +**This endpoint allows you to delete one or more recipients.** + +The body of an API call to this endpoint must include an array of recipient IDs of the recipients you want to delete. + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### DELETE /contactdb/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve the count of billable recipients + +**This endpoint allows you to retrieve the number of Marketing Campaigns recipients that you will be billed for.** + +You are billed for marketing campaigns based on the highest number of recipients you have had in your account at one time. This endpoint will allow you to know the current billable count value. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/recipients/billable_count + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/billable_count"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a Count of Recipients + +**This endpoint allows you to retrieve the total number of Marketing Campaigns recipients.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### GET /contactdb/recipients/count + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/count"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve recipients matching search criteria + +**This endpoint allows you to perform a search on all of your Marketing Campaigns recipients.** + +field_name: + +* is a variable that is substituted for your actual custom field name from your recipient. +* Text fields must be URL-encoded. Date fields are searchable only by Unix timestamp (e.g. 2/2/2015 becomes 1422835200) +* If field_name is a 'reserved' date field, such as created_at or updated_at, the system will internally convert + your epoch time to a date range encompassing the entire day. For example, an epoch time of 1422835600 converts to + Mon, 02 Feb 2015 00:06:40 GMT, but internally the system will search from Mon, 02 Feb 2015 00:00:00 GMT through + Mon, 02 Feb 2015 23:59:59 GMT. + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### GET /contactdb/recipients/search + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/search"); + request.addQueryParam("{field_name}", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a single recipient + +**This endpoint allows you to retrieve a single recipient by ID from your contact database.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/recipients/{recipient_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Recipient + +**This endpoint allows you to delete a single recipient with the given ID from your contact database.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### DELETE /contactdb/recipients/{recipient_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve the lists that a recipient is on + +**This endpoint allows you to retrieve the lists that a given recipient belongs to.** + +Each recipient can be on many lists. This endpoint gives you all of the lists that any one recipient has been added to. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +### GET /contactdb/recipients/{recipient_id}/lists + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}/lists"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve reserved fields + +**This endpoint allows you to list all fields that are reserved and can't be used for custom field names.** + +The contactdb is a database of your contacts for [Twilio SendGrid Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html). + +### GET /contactdb/reserved_fields + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/reserved_fields"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create a Segment + +**This endpoint allows you to create a segment.** + +All recipients in your contactdb will be added or removed automatically depending on whether they match the criteria for this segment. + +List Id: + +* Send this to segment from an existing list +* Don't send this in order to segment from your entire contactdb. + +Valid operators for create and update depend on the type of the field you are segmenting: + +* **Dates:** "eq", "ne", "lt" (before), "gt" (after) +* **Text:** "contains", "eq" (is - matches the full field), "ne" (is not - matches any field where the entire field is not the condition value) +* **Numbers:** "eq", "lt", "gt" +* **Email Clicks and Opens:** "eq" (opened), "ne" (not opened) + +Segment conditions using "eq" or "ne" for email clicks and opens should provide a "field" of either *clicks.campaign_identifier* or *opens.campaign_identifier*. The condition value should be a string containing the id of a completed campaign. + +Segments may contain multiple conditions, joined by an "and" or "or" in the "and_or" field. The first condition in the conditions list must have an empty "and_or", and subsequent conditions must all specify an "and_or". + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### POST /contactdb/segments + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/segments"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and)_or\":\"\",\"value\":\"Miller\"},{\"operator\":\"gt\",\"field\":\"last_clicked\",\"and_or\":\"and\",\"value\":\"01/02/2015\"},{\"operator\":\"eq\",\"field\":\"clicks.campaign_identifier\",\"and_or\":\"or\",\"value\":\"513\"}],\"name\":\"Last Name Miller\",\"list_id\":4}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all segments + +**This endpoint allows you to retrieve all of your segments.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### GET /contactdb/segments + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a segment + +**This endpoint allows you to update a segment.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### PATCH /contactdb/segments/{segment_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and)_or\":\"\",\"value\":\"Miller\"}],\"name\":\"The Millers\",\"list_id\":5}"); + request.addQueryParam("segment_id", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a segment + +**This endpoint allows you to retrieve a single segment with the given ID.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### GET /contactdb/segments/{segment_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("segment_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a segment + +**This endpoint allows you to delete a segment from your recipient's database.** + +You also have the option to delete all the contacts from your Marketing Campaigns recipient database who were in this segment. + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### DELETE /contactdb/segments/{segment_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve recipients on a segment + +**This endpoint allows you to retrieve all of the recipients in a segment with the given ID.** + +The Contacts API helps you manage your [Marketing Campaigns](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/index.html) recipients. + +For more information about segments in Marketing Campaigns, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/lists.html#-Create-a-Segment). + +### GET /contactdb/segments/{segment_id}/recipients + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# DEVICES + +## Retrieve email statistics by device type. + +**This endpoint allows you to retrieve your email statistics segmented by the device type.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +## Available Device Types +| **Device** | **Description** | **Example** | +|---|---|---| +| Desktop | Email software on desktop computer. | I.E., Outlook, Sparrow, or Apple Mail. | +| Webmail | A web-based email client. | I.E., Yahoo, Google, AOL, or Outlook.com. | +| Phone | A smartphone. | iPhone, Android, Blackberry, etc. +| Tablet | A tablet computer. | iPad, Android based tablet, etc. | +| Other | An unrecognized device. | + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /devices/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("devices/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# GEO + +## Retrieve email statistics by country and state/province. + +**This endpoint allows you to retrieve your email statistics segmented by country and state/province.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /geo/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("geo/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("country", "US"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# IPS + +## Retrieve all IP addresses + +**This endpoint allows you to retrieve a list of all assigned and unassigned IPs.** + +The response includes warm-up status, pools, assigned subusers, and authorization info. The start_date field corresponds to when warmup started for that IP. + +A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. + +### GET /ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("exclude_whitelabels", "true"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all assigned IPs + +**This endpoint allows you to retrieve only assigned IP addresses.** + +A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. + +### GET /ips/assigned + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/assigned"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create an IP pool. + +**This endpoint allows you to create an IP pool.** + +**Each user can create up to 10 different IP pools.** + +IP Pools allow you to group your dedicated Twilio SendGrid IP addresses together. For example, you could create separate pools for your transactional and marketing email. When sending marketing emails, specify that you want to use the marketing IP pool. This allows you to maintain separate reputations for your different email traffic. + +IP pools can only be used with authenticated IP addresses. + +If an IP pool is NOT specified for an email, it will use any IP available, including ones in pools. + +### POST /ips/pools + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools"); + request.setBody("{\"name\":\"marketing\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all IP pools. + +**This endpoint allows you to retrieve all of your IP pools.** + +IP Pools allow you to group your dedicated Twilio SendGrid IP addresses together. For example, you could create separate pools for your transactional and marketing email. When sending marketing emails, specify that you want to use the marketing IP pool. This allows you to maintain separate reputations for your different email traffic. + +IP pools can only be used with authenticated IP addresses. + +If an IP pool is NOT specified for an email, it will use any IP available, including ones in pools. + +### GET /ips/pools + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update an IP pools name. + +**This endpoint allows you to update the name of an IP pool.** + +IP Pools allow you to group your dedicated Twilio SendGrid IP addresses together. For example, you could create separate pools for your transactional and marketing email. When sending marketing emails, specify that you want to use the marketing IP pool. This allows you to maintain separate reputations for your different email traffic. + +IP pools can only be used with authenticated IP addresses. + +If an IP pool is NOT specified for an email, it will use any IP available, including ones in pools. + +### PUT /ips/pools/{pool_name} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("ips/pools/{pool_name}"); + request.setBody("{\"name\":\"new_pool_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all IPs in a specified pool. + +**This endpoint allows you to list all of the IP addresses that are in a specific IP pool.** + +IP Pools allow you to group your dedicated Twilio SendGrid IP addresses together. For example, you could create separate pools for your transactional and marketing email. When sending marketing emails, specify that you want to use the marketing IP pool. This allows you to maintain separate reputations for your different email traffic. + +IP pools can only be used with authenticated IP addresses. + +If an IP pool is NOT specified for an email, it will use any IP available, including ones in pools. + +### GET /ips/pools/{pool_name} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete an IP pool. + +**This endpoint allows you to delete an IP pool.** + +IP Pools allow you to group your dedicated Twilio SendGrid IP addresses together. For example, you could create separate pools for your transactional and marketing email. When sending marketing emails, specify that you want to use the marketing IP pool. This allows you to maintain separate reputations for your different email traffic. + +IP pools can only be used with authenticated IP addresses. + +If an IP pool is NOT specified for an email, it will use any IP available, including ones in pools. + +### DELETE /ips/pools/{pool_name} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add an IP address to a pool + +**This endpoint allows you to add an IP address to an IP pool.** + +You can add the same IP address to multiple pools. It may take up to 60 seconds for your IP address to be added to a pool after your request is made. + +A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. + +### POST /ips/pools/{pool_name}/ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools/{pool_name}/ips"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Remove an IP address from a pool. + +**This endpoint allows you to remove an IP address from an IP pool.** + +The same IP address can be added to multiple IP pools. + +A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. + +### DELETE /ips/pools/{pool_name}/ips/{ip} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}/ips/{ip}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Add an IP to warm up + +**This endpoint allows you to enter an IP address into warmup mode.** + +Twilio SendGrid can automatically warm up dedicated IP addresses by limiting the amount of mail that can be sent through them per hour, with the limit determined by how long the IP address has been in warmup. See the [warmup schedule](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_warmup_schedule.html) for more details on how Twilio SendGrid limits your email traffic for IPs in warmup. + +For more general information about warming up IPs, please see our [Classroom](https://sendgrid.com/docs/Classroom/Deliver/Delivery_Introduction/warming_up_ips.html). + +### POST /ips/warmup + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/warmup"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all IPs currently in warmup + +**This endpoint allows you to retrieve all of your IP addresses that are currently warming up.** + +Twilio SendGrid can automatically warm up dedicated IP addresses by limiting the amount of mail that can be sent through them per hour, with the limit determined by how long the IP address has been in warmup. See the [warmup schedule](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_warmup_schedule.html) for more details on how Twilio SendGrid limits your email traffic for IPs in warmup. + +For more general information about warming up IPs, please see our [Classroom](https://sendgrid.com/docs/Classroom/Deliver/Delivery_Introduction/warming_up_ips.html). + +### GET /ips/warmup + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve warmup status for a specific IP address + +**This endpoint allows you to retrieve the warmup status for a specific IP address.** + +Twilio SendGrid can automatically warm up dedicated IP addresses by limiting the amount of mail that can be sent through them per hour, with the limit determined by how long the IP address has been in warmup. See the [warmup schedule](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_warmup_schedule.html) for more details on how Twilio SendGrid limits your email traffic for IPs in warmup. + +For more general information about warming up IPs, please see our [Classroom](https://sendgrid.com/docs/Classroom/Deliver/Delivery_Introduction/warming_up_ips.html). + +### GET /ips/warmup/{ip_address} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Remove an IP from warmup + +**This endpoint allows you to remove an IP address from warmup mode.** + +Twilio SendGrid can automatically warm up dedicated IP addresses by limiting the amount of mail that can be sent through them per hour, with the limit determined by how long the IP address has been in warmup. See the [warmup schedule](https://sendgrid.com/docs/API_Reference/Web_API_v3/IP_Management/ip_warmup_schedule.html) for more details on how Twilio SendGrid limits your email traffic for IPs in warmup. + +For more general information about warming up IPs, please see our [Classroom](https://sendgrid.com/docs/Classroom/Deliver/Delivery_Introduction/warming_up_ips.html). + +### DELETE /ips/warmup/{ip_address} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all IP pools an IP address belongs to + +**This endpoint allows you to see which IP pools a particular IP address has been added to.** + +The same IP address can be added to multiple IP pools. + +A single IP address or a range of IP addresses may be dedicated to an account in order to send email for multiple domains. The reputation of this IP is based on the aggregate performance of all the senders who use it. + +### GET /ips/{ip_address} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# MAIL + +## Create a batch ID + +**This endpoint allows you to generate a new batch ID. This batch ID can be associated with scheduled sends via the mail/send endpoint.** + +If you set the SMTPAPI header, `batch_id`, it allows you to then associate multiple scheduled mail/send requests together with the same ID. Then at any time up to 10 minutes before the scheduled date, you can cancel all of the mail/send requests that have this batch ID by calling the Cancel Scheduled Send endpoint. + +More Information: + +* [Scheduling Parameters > Batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) + +### POST /mail/batch + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/batch"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Validate batch ID + +**This endpoint allows you to validate a batch ID.** + +If you set the SMTPAPI header, `batch_id`, it allows you to then associate multiple scheduled mail/send requests together with the same ID. Then at any time up to 10 minutes before the scheduled date, you can cancel all of the mail/send requests that have this batch ID by calling the Cancel Scheduled Send endpoint. + +More Information: + +* [Scheduling Parameters > Batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) + +### GET /mail/batch/{batch_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail/batch/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## v3 Mail Send + +This endpoint allows you to send an email over Twilio SendGrid's v3 Web API, the most recent version of our API. If you are looking for documentation about the v2 Mail Send endpoint, please see our [v2 API Reference](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). + +* Top level parameters are referred to as "global". +* Individual fields within the personalizations array will override any other global, or message level, parameters that are defined outside of personalizations. + +For an overview of the v3 Mail Send endpoint, please visit our [v3 API Reference](https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html) + +For more detailed information about how to use the v3 Mail Send endpoint, please visit our [Classroom](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/index.html). + +### POST /mail/send + +This endpoint has a helper, check it out [here](src/main/java/com/sendgrid/helpers/README.md). + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\")[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"from\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"attachments\":[{\"name\":\"file1\",\"filename\":\"file1.jpg\",\"content\":\"[BASE64 encoded content block here]\",\"disposition\":\"inline\",\"content_id\":\"ii_139db99fdb5c3704\",\"type\":\"jpg\"}],\"personalizations\":[{\"to\":[{\"email\":\"john.doe@example.com\",\"name\":\"John Doe\"}],\"cc\":[{\"email\":\"jane.doe@example.com\",\"name\":\"Jane Doe\"}],\"bcc\":[{\"email\":\"sam.doe@example.com\",\"name\":\"Sam Doe\"}],\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\"[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"headers\":{\"X-Accept-Language\":\"en\",\"X-Mailer\":\"MyApp\"},\"send_at\":1409348513,\"substitutions\":{\"type\":\"object\",\"id\":\"substitutions\"},\"subject\":\"Hello, World!\"}],\"subject\":\"Hello, World!\",\"ip_pool_name\":\"[YOUR POOL NAME GOES HERE]\",\"content\":[{\"type\":\"text/html\",\"value\":\"

Hello, world!

\"}],\"headers\":{},\"asm\":{\"groups_to_display\":[1,2,3],\"group_id\":1},\"batch_id\":\"[YOUR BATCH ID GOES HERE]\",\"tracking_settings\":{\"subscription_tracking\":{\"text\":\"If you would like to unsubscribe and stop receiving these emails <% click here %>.\",\"enable\":true,\"html\":\"If you would like to unsubscribe and stop receiving these emails <% clickhere %>.\",\"substitution_tag\":\"<%click here%>\"},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"%opentrack\"},\"click_tracking\":{\"enable\":true,\"enable_text\":true},\"ganalytics\":{\"utm_campaign\":\"[NAME OF YOUR REFERRER SOURCE]\",\"enable\":true,\"utm_name\":\"[NAME OF YOUR CAMPAIGN]\",\"utm_term\":\"[IDENTIFY PAID KEYWORDS HERE]\",\"utm_content\":\"[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]\",\"utm_medium\":\"[NAME OF YOUR MARKETING MEDIUM e.g. email]\"}},\"mail_settings\":{\"footer\":{\"text\":\"Thanks,/n The Twilio SendGrid Team\",\"enable\":true,\"html\":\"

Thanks
The Twilio SendGrid Team

\"},\"spam_check\":{\"threshold\":3,\"post_to_url\":\"http://example.com/compliance\",\"enable\":true},\"bypass_list_management\":{\"enable\":true},\"sandbox_mode\":{\"enable\":false},\"bcc\":{\"enable\":true,\"email\":\"ben.doe@example.com\"}},\"reply_to\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"sections\":{\"section\":{\":sectionName2\":\"section 2 text\",\":sectionName1\":\"section 1 text\"}},\"template_id\":\"[YOUR TEMPLATE ID GOES HERE]\",\"categories\":[\"category1\",\"category2\"],\"send_at\":1409348513}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# MAIL SETTINGS + +## Retrieve all mail settings + +**This endpoint allows you to retrieve a list of all mail settings.** + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update address whitelist mail settings + +**This endpoint allows you to update your current email address whitelist settings.** + +The address whitelist setting whitelists a specified email address or domain for which mail should never be suppressed. For example, you own the domain example.com, and one or more of your recipients use email@example.com addresses, by placing example.com in the address whitelist setting, all bounces, blocks, and unsubscribes logged for that domain will be ignored and sent as if under normal sending conditions. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/address_whitelist + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/address_whitelist"); + request.setBody("{\"list\":[\"email1@example.com\",\"example.com\"],\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve address whitelist mail settings + +**This endpoint allows you to retrieve your current email address whitelist settings.** + +The address whitelist setting whitelists a specified email address or domain for which mail should never be suppressed. For example, you own the domain example.com, and one or more of your recipients use email@example.com addresses, by placing example.com in the address whitelist setting, all bounces, blocks, and unsubscribes logged for that domain will be ignored and sent as if under normal sending conditions. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/address_whitelist + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/address_whitelist"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update BCC mail settings + +**This endpoint allows you to update your current BCC mail settings.** + +When the BCC mail setting is enabled, Twilio SendGrid will automatically send a blind carbon copy (BCC) to an address for every email sent without adding that address to the header. Please note that only one email address may be entered in this field if you wish to distribute BCCs to multiple addresses you will need to create a distribution group or use forwarding rules. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/bcc + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bcc"); + request.setBody("{\"enabled\":false,\"email\":\"email@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all BCC mail settings + +**This endpoint allows you to retrieve your current BCC mail settings.** + +When the BCC mail setting is enabled, Twilio SendGrid will automatically send a blind carbon copy (BCC) to an address for every email sent without adding that address to the header. Please note that only one email address may be entered in this field if you wish to distribute BCCs to multiple addresses you will need to create a distribution group or use forwarding rules. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/bcc + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bcc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update bounce purge mail settings + +**This endpoint allows you to update your current bounce purge settings.** + +This setting allows you to set a schedule for Twilio SendGrid to automatically delete contacts from your soft and hard bounce suppression lists. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/bounce_purge + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bounce_purge"); + request.setBody("{\"hard_bounces\":5,\"soft_bounces\":5,\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve bounce purge mail settings + +**This endpoint allows you to retrieve your current bounce purge settings.** + +This setting allows you to set a schedule for Twilio SendGrid to automatically delete contacts from your soft and hard bounce suppression lists. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/bounce_purge + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bounce_purge"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update footer mail settings + +**This endpoint allows you to update your current Footer mail settings.** + +The footer setting will insert a custom footer at the bottom of the text and HTML bodies. Use the embedded HTML editor and plain text entry fields to create the content of the footers to be inserted into your emails. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/footer + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/footer"); + request.setBody("{\"html_content\":\"...\",\"enabled\":true,\"plain_content\":\"...\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve footer mail settings + +**This endpoint allows you to retrieve your current Footer mail settings.** + +The footer setting will insert a custom footer at the bottom of the text and HTML bodies. Use the embedded HTML editor and plain text entry fields to create the content of the footers to be inserted into your emails. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/footer + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/footer"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update forward bounce mail settings + +**This endpoint allows you to update your current bounce forwarding mail settings.** + +Activating this setting allows you to specify an email address to which bounce reports are forwarded. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/forward_bounce + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_bounce"); + request.setBody("{\"enabled\":true,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve forward bounce mail settings + +**This endpoint allows you to retrieve your current bounce forwarding mail settings.** + +Activating this setting allows you to specify an email address to which bounce reports are forwarded. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/forward_bounce + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_bounce"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update forward spam mail settings + +**This endpoint allows you to update your current Forward Spam mail settings.** + +Enabling the forward spam setting allows you to specify an email address to which spam reports will be forwarded. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/forward_spam + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_spam"); + request.setBody("{\"enabled\":false,\"email\":\"\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve forward spam mail settings + +**This endpoint allows you to retrieve your current Forward Spam mail settings.** + +Enabling the forward spam setting allows you to specify an email address to which spam reports will be forwarded. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/forward_spam + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_spam"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update plain content mail settings + +**This endpoint allows you to update your current Plain Content mail settings.** + +The plain content setting will automatically convert any plain text emails that you send to HTML before sending. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/plain_content + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/plain_content"); + request.setBody("{\"enabled\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve plain content mail settings + +**This endpoint allows you to retrieve your current Plain Content mail settings.** + +The plain content setting will automatically convert any plain text emails that you send to HTML before sending. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/plain_content + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/plain_content"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update spam check mail settings + +**This endpoint allows you to update your current spam checker mail settings.** + +The spam checker filter notifies you when emails are detected that exceed a predefined spam threshold. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/spam_check + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/spam_check"); + request.setBody("{\"url\":\"url\",\"max_score\":5,\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve spam check mail settings + +**This endpoint allows you to retrieve your current Spam Checker mail settings.** + +The spam checker filter notifies you when emails are detected that exceed a predefined spam threshold. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/spam_check + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/spam_check"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update template mail settings + +**This endpoint allows you to update your current legacy email template settings.** + +This setting refers to our original email templates. We currently support more fully featured [transactional templates](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +The legacy email template setting wraps an HTML template around your email content. This can be useful for sending out marketing email and/or other HTML formatted messages. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### PATCH /mail_settings/template + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/template"); + request.setBody("{\"html_content\":\"<% body %>\",\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve legacy template mail settings + +**This endpoint allows you to retrieve your current legacy email template settings.** + +This setting refers to our original email templates. We currently support more fully featured [transactional templates](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +The legacy email template setting wraps an HTML template around your email content. This can be useful for sending out marketing email and/or other HTML formatted messages. + +Mail settings allow you to tell Twilio SendGrid specific things to do to every email that you send to your recipients over Twilio SendGrid's [Web API](https://sendgrid.com/docs/API_Reference/Web_API/mail.html) or [SMTP Relay](https://sendgrid.com/docs/API_Reference/SMTP_API/index.html). + +### GET /mail_settings/template + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/template"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# MAILBOX PROVIDERS + +## Retrieve email statistics by mailbox provider. + +**This endpoint allows you to retrieve your email statistics segmented by recipient mailbox provider.** + +**We only store up to 7 days of email activity in our database.** By default, 500 items will be returned per request via the Advanced Stats API endpoints. + +Advanced Stats provide a more in-depth view of your email statistics and the actions taken by your recipients. You can segment these statistics by geographic location, device type, client type, browser, and mailbox provider. For more information about statistics, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/index.html). + +### GET /mailbox_providers/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mailbox_providers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("mailbox_providers", "test_string"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# PARTNER SETTINGS + +## Returns a list of all partner settings. + +**This endpoint allows you to retrieve a list of all partner settings that you can enable.** + +Our partner settings allow you to integrate your Twilio SendGrid account with our partners to increase your Twilio SendGrid experience and functionality. For more information about our partners, and how you can begin integrating with them, please visit our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/partners.html). + +### GET /partner_settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Updates New Relic partner settings. + +**This endpoint allows you to update or change your New Relic partner settings.** + +Our partner settings allow you to integrate your Twilio SendGrid account with our partners to increase your Twilio SendGrid experience and functionality. For more information about our partners, and how you can begin integrating with them, please visit our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/partners.html). + +By integrating with New Relic, you can send your Twilio SendGrid email statistics to your New Relic Dashboard. If you enable this setting, your stats will be sent to New Relic every 5 minutes. You will need your New Relic License Key to enable this setting. For more information, please see our [Classroom](https://sendgrid.com/docs/Classroom/Track/Collecting_Data/new_relic.html). + +### PATCH /partner_settings/new_relic + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("partner_settings/new_relic"); + request.setBody("{\"enable_subuser_statistics\":true,\"enabled\":true,\"license_key\":\"\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Returns all New Relic partner settings. + +**This endpoint allows you to retrieve your current New Relic partner settings.** + +Our partner settings allow you to integrate your Twilio SendGrid account with our partners to increase your Twilio SendGrid experience and functionality. For more information about our partners, and how you can begin integrating with them, please visit our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/partners.html). + +By integrating with New Relic, you can send your Twilio SendGrid email statistics to your New Relic Dashboard. If you enable this setting, your stats will be sent to New Relic every 5 minutes. You will need your New Relic License Key to enable this setting. For more information, please see our [Classroom](https://sendgrid.com/docs/Classroom/Track/Collecting_Data/new_relic.html). + +### GET /partner_settings/new_relic + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings/new_relic"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# SCOPES + +## Retrieve a list of scopes for which this user has access. + +**This endpoint returns a list of all scopes that this user has access to.** + +API Keys can be used to authenticate the use of [Twilio SendGrid's v3 Web API](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html), or the [Mail API Endpoint](https://sendgrid.com/docs/API_Reference/Web_API/mail.html). API Keys may be assigned certain permissions, or scopes, that limit which API endpoints they are able to access. For a more detailed explanation of how you can use API Key permissions, please visit our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/api_keys.html#-API-Key-Permissions) or [Classroom](https://sendgrid.com/docs/Classroom/Basics/API/api_key_permissions.html). + +### GET /scopes + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("scopes"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# SENDERS + +## Create a Sender Identity + +**This endpoint allows you to create a new sender identity.** + +*You may create up to 100 unique sender identities.* + +Sender Identities are required to be verified before use. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +### POST /senders + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example) INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Get all Sender Identities + +**This endpoint allows you to retrieve a list of all sender identities that have been created for your account.** + +Sender Identities are required to be verified before use. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +### GET /senders + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a Sender Identity + +**This endpoint allows you to update a sender identity.** + +Updates to `from.email` require re-verification. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +Partial updates are allowed, but fields that are marked as "required" in the POST (create) endpoint must not be nil if that field is included in the PATCH request. + +### PATCH /senders/{sender_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("senders/{sender_id}"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example) INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## View a Sender Identity + +**This endpoint allows you to retrieve a specific sender identity.** + +Sender Identities are required to be verified before use. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +### GET /senders/{sender_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a Sender Identity + +**This endpoint allows you to delete one of your sender identities.** + +Sender Identities are required to be verified before use. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +### DELETE /senders/{sender_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Resend Sender Identity Verification + +**This endpoint allows you to resend a sender identity verification email.** + +Sender Identities are required to be verified before use. If your domain has been authorized, it will auto verify on creation. Otherwise, an email will be sent to the `from.email`. + +### POST /senders/{sender_id}/resend_verification + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders/{sender_id}/resend_verification"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# SENDER AUTHENTICATION + +## Create an authenticated domain. + +**This endpoint allows you to create a domain authentication for one of your domains.** + +If you are creating a domain authentication that you would like a subuser to use, you have two options: +1. Use the "username" parameter. This allows you to create am authenticated subuser. This means the subuser is able to see and modify the created authentication. +2. Use the Association workflow (see Associate Domain section). This allows you to assign a domain authentication created by the parent to a subuser. This means the subuser will default to the assigned domain authentication, but will not be able to see or modify that authentication. However, if the subuser creates their own domain authentication it will overwrite the assigned domain authentication. + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +### POST /whitelabel/domains + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains"); + request.setBody("{\"automatic)_security\":false,\"username\":\"john@example.com\",\"domain\":\"example.com\",\"default\":true,\"custom_spf\":true,\"ips\":[\"192.168.1.1\",\"192.168.1.2\"],\"subdomain\":\"news\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## List all domain authentications. + +**This endpoint allows you to retrieve a list of all domain authentications you have created.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +### GET /whitelabel/domains + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("domain", "test_string"); + request.addQueryParam("exclude_subusers", "true"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Get the default domain authentication. + +**This endpoint allows you to retrieve the default authentication for a domain.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| domain | string |The domain to find a default domain whitelabel for. | + +### GET /whitelabel/domains/default + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/default"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## List the domain authentication associated with the given user. + +**This endpoint allows you to retrieve all of the domain authentications that have been assigned to a specific subuser.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +Domain authentications can be associated with (i.e. assigned to) subusers from a parent account. This functionality allows subusers to send mail using their parent's authenticated domains. To associate a domain authentication with a subuser, the parent account must first create the domain authentication and validate it. The parent may then associate the domain authentication via the subuser management tools. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| username | string | Username of the subuser to find associated whitelabels for. | + +### GET /whitelabel/domains/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Disassociate a domain authentication from a given user. + +**This endpoint allows you to disassociate a specific domain authentication from a subuser.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +Domain authentications can be associated with (i.e. assigned to) subusers from a parent account. This functionality allows subusers to send mail using their parent's authenticated domains. To associate a domain authentication with a subuser, the parent account must first create the domain authentication and validate it. The parent may then associate the domain authentication via the subuser management tools. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Required? | Description | +|---|---|---|---| +| username | string | required | Username for the subuser to find associated whitelabels for. | + +### DELETE /whitelabel/domains/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Update a domain authentication. + +**This endpoint allows you to update the settings for a domain authentication.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +### PATCH /whitelabel/domains/{domain_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/domains/{domain_id}"); + request.setBody("{\"default\":false,\"custom_spf\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve a domain authentication. + +**This endpoint allows you to retrieve a specific domain authentication.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + + +### GET /whitelabel/domains/{domain_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Delete a domain authentication. + +**This endpoint allows you to delete a domain authentication.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +### DELETE /whitelabel/domains/{domain_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Associate a domain authentication with a given user. + +**This endpoint allows you to associate a specific domain authentication with a subuser.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +Domain authentications can be associated with (i.e. assigned to) subusers from a parent account. This functionality allows subusers to send mail using their parent's authenticated domains. To associate a domain authentication with a subuser, the parent account must first create the domain authentication and validate it. The parent may then associate the domain authentication via the subuser management tools. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| domain_id | integer | ID of the domain whitelabel to associate with the subuser. | + +### POST /whitelabel/domains/{domain_id}/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{domain_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Add an IP to a domain authentication. + +**This endpoint allows you to add an IP address to a domain authentication.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| id | integer | ID of the domain to which you are adding an IP | + +### POST /whitelabel/domains/{id}/ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/ips"); + request.setBody("{\"ip\":\"192.168.0.1\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Remove an IP from a domain authentication. + +**This endpoint allows you to remove a domain's IP address from that domain's authentication.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| id | integer | ID of the domain whitelabel to delete the IP from. | +| ip | string | IP to remove from the domain whitelabel. | + +### DELETE /whitelabel/domains/{id}/ips/{ip} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{id}/ips/{ip}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Validate a domain authentication. + +**This endpoint allows you to validate a domain authentication. If it fails, it will return an error message describing why the domain could not be validated.** + +A domain authentication allows you to remove the via or sent on behalf of message that your recipients see when they read your emails. Authenticating a domain allows you to replace sendgrid.net with your personal sending domain. You will be required to create a subdomain so that Twilio SendGrid can generate the DNS records which you must give to your host provider. If you choose to use Automated Security, Twilio SendGrid will provide you with 3 CNAME records. If you turn Automated Security off, you will be given 2 TXT records and 1 MX record. + +For more information on domain authentication, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| id | integer |ID of the domain whitelabel to validate. | + +### POST /whitelabel/domains/{id}/validate + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Create reverse DNS + +**This endpoint allows you to create a reverse DNS record.** + +When creating a reverse DNS record, you should use the same subdomain that you used when you created a domain authentication. + +Reverse DNS consists of a subdomain and domain that will be used to generate a record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/). + +### POST /whitelabel/ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips"); + request.setBody("{\"ip\":\"192.168.1.1\",\"domain\":\"example.com\",\"subdomain\":\"email\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve all reverse DNS records + +**This endpoint allows you to retrieve all of the reverse DNS records that have been created by this account.** + +You may include a search key by using the "ip" parameter. This enables you to perform a prefix search for a given IP segment (e.g. "192."). + +Reverse DNS consists of a subdomain and domain that will be used to generate a record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/). + +### GET /whitelabel/ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve an reverse DNS record + +**This endpoint allows you to retrieve a reverse DNS record.** + +Reverse DNS consists of a subdomain and domain that will be used to generate a record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/). + +### GET /whitelabel/ips/{id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Delete an reverse DNS record + +**This endpoint allows you to delete a reverse DNS record.** + +Reverse DNS consists of a subdomain and domain that will be used to generate a record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/). + +### DELETE /whitelabel/ips/{id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Validate a reverse DNS record + +**This endpoint allows you to validate a reverse DNS record.** + +Reverse DNS consists of a subdomain and domain that will be used to generate a record for a given IP. Once Twilio SendGrid has verified that the appropriate A record for the IP has been created, the appropriate reverse DNS record for the IP is generated. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/). + +### POST /whitelabel/ips/{id}/validate + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Create a Branded Link + +**This endpoint allows you to create a new link branding.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### POST /whitelabel/links + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links"); + request.setBody("{\"default\":true,\"domain\":\"example.com\",\"subdomain\":\"mail\"}"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve all link brandings + +**This endpoint allows you to retrieve all link brandings.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### GET /whitelabel/links + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve a Default Link Branding + +**This endpoint allows you to retrieve the default link branding.** + +Default link branding is the actual link branding to be used when sending messages. If there are multiple link brandings, the default is determined by the following order: +
    +
  • Validated link branding marked as "default"
  • +
  • Legacy link brands (migrated from the whitelabel wizard)
  • +
  • Default Twilio SendGrid link whitelabel (i.e. 100.ct.sendgrid.net)
  • +
+ +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### GET /whitelabel/links/default + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/default"); + request.addQueryParam("domain", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve Associated Link Branding + +**This endpoint allows you to retrieve the associated link branding for a subuser.** + +Link branding can be associated with subusers from the parent account. This functionality allows +subusers to send mail using their parent's link brands. To associate a link branding, the parent account +must first create a branded link and validate it. The parent may then associate that branded link with a subuser via the API or the Subuser Management page in the user interface. + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### GET /whitelabel/links/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Disassociate a Link Branding + +**This endpoint allows you to disassociate a link branding from a subuser.** + +Link branding can be associated with subusers from the parent account. This functionality allows +subusers to send mail using their parent's link brands. To associate a link branding, the parent account +must first create a branded link and validate it. The parent may then associate that branded link with a subuser via the API or the Subuser Management page in the user interface. + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### DELETE /whitelabel/links/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Update a Link Branding + +**This endpoint allows you to update a specific link branding. You can use this endpoint to change a branded link's default status.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### PATCH /whitelabel/links/{id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/links/{id}"); + request.setBody("{\"default\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Retrieve a Link Branding + +**This endpoint allows you to retrieve a specific link branding.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### GET /whitelabel/links/{id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Delete a Link Branding + +**This endpoint allows you to delete a link branding.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### DELETE /whitelabel/links/{id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Validate a Link Branding + +**This endpoint allows you to validate a link branding.** + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### POST /whitelabel/links/{id}/validate + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` +## Associate a Link Branding + +**This endpoint allows you to associate a link branding with a subuser account.** + +Link branding can be associated with subusers from the parent account. This functionality allows +subusers to send mail using their parent's link brands. To associate a link branding, the parent account +must first create a branded link and validate it. The parent may then associate that branded link with a subuser via the API or the Subuser Management page in the user interface. + +Email link branding allow all of the click-tracked links you send in your emails to include the URL of your domain instead of sendgrid.net. + +For more information, please see our [User Guide](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-link-branding/). + +### POST /whitelabel/links/{link_id}/subuser + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{link_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + ``` + + +# STATS + +## Retrieve global email statistics + +**This endpoint allows you to retrieve all of your global email statistics between a given date range.** + +Parent accounts will see aggregated stats for their account and all subuser accounts. Subuser accounts will only see their own stats. + +### GET /stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# SUBUSERS + +## Create Subuser + +This endpoint allows you to retrieve a list of all of your subusers. You can choose to retrieve specific subusers as well as limit the results that come back from the API. + +For more information about Subusers: + +* [User Guide > Subusers](https://sendgrid.com/docs/User_Guide/Settings/Subusers/index.html) +* [Classroom > How do I add more subusers to my account?](https://sendgrid.com/docs/Classroom/Basics/Account/how_do_i_add_more_subusers_to_my_account.html) + +### POST /subusers + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers"); + request.setBody("{\"username\":\"John@example.com\",\"ips\":[\"1.1.1.1\",\"2.2.2.2\"],\"password\":\"johns_password\",\"email\)":\"John@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## List all Subusers + +This endpoint allows you to retrieve a list of all of your subusers. You can choose to retrieve specific subusers as well as limit the results that come back from the API. + +For more information about Subusers: + +* [User Guide > Subusers](https://sendgrid.com/docs/User_Guide/Settings/Subusers/index.html) +* [Classroom > How do I add more subusers to my account?](https://sendgrid.com/docs/Classroom/Basics/Account/how_do_i_add_more_subusers_to_my_account.html) + +### GET /subusers + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Subuser Reputations + +Subuser sender reputations give a good idea how well a sender is doing with regards to how recipients and recipient servers react to the mail that is being received. When a bounce, spam report, or other negative action happens on a sent email, it will affect your sender rating. + +This endpoint allows you to request the reputations for your subusers. + +### GET /subusers/reputations + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/reputations"); + request.addQueryParam("usernames", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve email statistics for your subusers. + +**This endpoint allows you to retrieve the email statistics for the given subusers.** + +You may retrieve statistics for up to 10 different subusers by including an additional _subusers_ parameter for each additional subuser. + +While you can always view the statistics for all email activity on your account, subuser statistics enable you to view specific segments of your stats. Emails sent, bounces, and spam reports are always tracked for subusers. Unsubscribes, clicks, and opens are tracked if you have enabled the required settings. + +For more information, see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/subuser.html). + +### GET /subusers/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("subusers", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve monthly stats for all subusers + +**This endpoint allows you to retrieve the monthly email statistics for all subusers over the given date range.** + +While you can always view the statistics for all email activity on your account, subuser statistics enable you to view specific segments of your stats for your subusers. Emails sent, bounces, and spam reports are always tracked for subusers. Unsubscribes, clicks, and opens are tracked if you have enabled the required settings. + +When using the `sort_by_metric` to sort your stats by a specific metric, you can not sort by the following metrics: +`bounce_drops`, `deferred`, `invalid_emails`, `processed`, `spam_report_drops`, `spam_reports`, or `unsubscribe_drops`. + +For more information, see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/subuser.html). + +### GET /subusers/stats/monthly + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/monthly"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve the totals for each email statistic metric for all subusers. + +**This endpoint allows you to retrieve the total sums of each email statistic metric for all subusers over the given date range.** + + +While you can always view the statistics for all email activity on your account, subuser statistics enable you to view specific segments of your stats. Emails sent, bounces, and spam reports are always tracked for subusers. Unsubscribes, clicks, and opens are tracked if you have enabled the required settings. + +For more information, see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/subuser.html). + +### GET /subusers/stats/sums + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Enable/disable a subuser + +This endpoint allows you to enable or disable a subuser. + +For more information about Subusers: + +* [User Guide > Subusers](https://sendgrid.com/docs/User_Guide/Settings/Subusers/index.html) +* [Classroom > How do I add more subusers to my account?](https://sendgrid.com/docs/Classroom/Basics/Account/how_do_i_add_more_subusers_to_my_account.html) + +### PATCH /subusers/{subuser_name} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("subusers/{subuser_name}"); + request.setBody("{\"disabled\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a subuser + +This endpoint allows you to delete a subuser. This is a permanent action, once deleted a subuser cannot be retrieved. + +For more information about Subusers: + +* [User Guide > Subusers](https://sendgrid.com/docs/User_Guide/Settings/Subusers/index.html) +* [Classroom > How do I add more subusers to my account?](https://sendgrid.com/docs/Classroom/Basics/Account/how_do_i_add_more_subusers_to_my_account.html) + +### DELETE /subusers/{subuser_name} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update IPs assigned to a subuser + +Each subuser should be assigned to an IP address, from which all of this subuser's mail will be sent. Often, this is the same IP as the parent account, but each subuser can have their own, or multiple, IP addresses as well. + +More information: + +* [How to request more IPs](https://sendgrid.com/docs/Classroom/Basics/Account/adding_an_additional_dedicated_ip_to_your_account.html) +* [How to set up reverse DNS](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-reverse-dns/) + +### PUT /subusers/{subuser_name}/ips + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/ips"); + request.setBody("[\"127.0.0.1\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Monitor Settings for a subuser + +Subuser monitor settings allow you to receive a sample of an outgoing message by a specific customer at a specific frequency of emails. + +### PUT /subusers/{subuser_name}/monitor + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":500,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create monitor settings + +Subuser monitor settings allow you to receive a sample of an outgoing message by a specific customer at a specific frequency of emails. + +### POST /subusers/{subuser_name}/monitor + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":50000,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve monitor settings for a subuser + +Subuser monitor settings allow you to receive a sample of an outgoing message by a specific customer at a specific frequency of emails. + +### GET /subusers/{subuser_name}/monitor + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete monitor settings + +Subuser monitor settings allow you to receive a sample of an outgoing message by a specific customer at a specific frequency of emails. + +### DELETE /subusers/{subuser_name}/monitor + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve the monthly email statistics for a single subuser + +**This endpoint allows you to retrieve the monthly email statistics for a specific subuser.** + +While you can always view the statistics for all email activity on your account, subuser statistics enable you to view specific segments of your stats for your subusers. Emails sent, bounces, and spam reports are always tracked for subusers. Unsubscribes, clicks, and opens are tracked if you have enabled the required settings. + +When using the `sort_by_metric` to sort your stats by a specific metric, you can not sort by the following metrics: +`bounce_drops`, `deferred`, `invalid_emails`, `processed`, `spam_report_drops`, `spam_reports`, or `unsubscribe_drops`. + +For more information, see our [User Guide](https://sendgrid.com/docs/User_Guide/Statistics/subuser.html). + +### GET /subusers/{subuser_name}/stats/monthly + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/stats/monthly"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# SUPPRESSION + +## Retrieve all blocks + +**This endpoint allows you to retrieve a list of all email addresses that are currently on your blocks list.** + +[Blocks](https://sendgrid.com/docs/Glossary/blocks.html) happen when your message was rejected for a reason related to the message, not the recipient address. This can happen when your mail server IP address has been added to a blacklist or blocked by an ISP, or if the message content is flagged by a filter on the receiving server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/blocks.html). + +### GET /suppression/blocks + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete blocks + +**This endpoint allows you to delete all email addresses on your blocks list.** + +There are two options for deleting blocked emails: + +1. You can delete all blocked emails by setting `delete_all` to true in the request body. +2. You can delete some blocked emails by specifying the email addresses in an array in the request body. + +[Blocks](https://sendgrid.com/docs/Glossary/blocks.html) happen when your message was rejected for a reason related to the message, not the recipient address. This can happen when your mail server IP address has been added to a blacklist or blocked by an ISP, or if the message content is flagged by a filter on the receiving server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/blocks.html). + +### DELETE /suppression/blocks + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific block + +**This endpoint allows you to retrieve a specific email address from your blocks list.** + +[Blocks](https://sendgrid.com/docs/Glossary/blocks.html) happen when your message was rejected for a reason related to the message, not the recipient address. This can happen when your mail server IP address has been added to a blacklist or blocked by an ISP, or if the message content is flagged by a filter on the receiving server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/blocks.html). + +### GET /suppression/blocks/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a specific block + +**This endpoint allows you to delete a specific email address from your blocks list.** + +[Blocks](https://sendgrid.com/docs/Glossary/blocks.html) happen when your message was rejected for a reason related to the message, not the recipient address. This can happen when your mail server IP address has been added to a blacklist or blocked by an ISP, or if the message content is flagged by a filter on the receiving server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/blocks.html). + +### DELETE /suppression/blocks/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all bounces + +**This endpoint allows you to retrieve all of your bounces.** + +Bounces are messages that are returned to the server that sent it. + +For more information see: + +* [User Guide > Bounces](https://sendgrid.com/docs/User_Guide/Suppressions/bounces.html) for more information +* [Glossary > Bounces](https://sendgrid.com/docs/Glossary/Bounces.html) + +### GET /suppression/bounces + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("end_time", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete bounces + +**This endpoint allows you to delete all of your bounces. You can also use this endpoint to remove a specific email address from your bounce list.** + +Bounces are messages that are returned to the server that sent it. + +For more information see: + +* [User Guide > Bounces](https://sendgrid.com/docs/User_Guide/Suppressions/bounces.html) for more information +* [Glossary > Bounces](https://sendgrid.com/docs/Glossary/Bounces.html) +* [Classroom > List Scrubbing Guide](https://sendgrid.com/docs/Classroom/Deliver/list_scrubbing.html) + +Note: the `delete_all` and `emails` parameters should be used independently of each other as they have different purposes. + +### DELETE /suppression/bounces + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces"); + request.setBody("{\"emails\":[\"example@example.com\",\"example2@example.com\"],\"delete_all\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a Bounce + +**This endpoint allows you to retrieve a specific bounce for a given email address.** + +Bounces are messages that are returned to the server that sent it. + +For more information see: + +* [User Guide > Bounces](https://sendgrid.com/docs/User_Guide/Suppressions/bounces.html) for more information +* [Glossary > Bounces](https://sendgrid.com/docs/Glossary/Bounces.html) +* [Classroom > List Scrubbing Guide](https://sendgrid.com/docs/Classroom/Deliver/list_scrubbing.html) + +### GET /suppression/bounces/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a bounce + +**This endpoint allows you to remove an email address from your bounce list.** + +Bounces are messages that are returned to the server that sent it. This endpoint allows you to delete a single email address from your bounce list. + +For more information see: + +* [User Guide > Bounces](https://sendgrid.com/docs/User_Guide/Suppressions/bounces.html) for more information +* [Glossary > Bounces](https://sendgrid.com/docs/Glossary/Bounces.html) +* [Classroom > List Scrubbing Guide](https://sendgrid.com/docs/Classroom/Deliver/list_scrubbing.html) + +### DELETE /suppression/bounces/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces/{email}"); + request.addQueryParam("email_address", "example@example.com"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all invalid emails + +**This endpoint allows you to retrieve a list of all invalid email addresses.** + +An invalid email occurs when you attempt to send email to an address that is formatted in a manner that does not meet internet email format standards or the email does not exist at the recipient's mail server. + +Examples include addresses without the @ sign or addresses that include certain special characters and/or spaces. This response can come from our own server or the recipient mail server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/invalid_emails.html). + +### GET /suppression/invalid_emails + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete invalid emails + +**This endpoint allows you to remove email addresses from your invalid email address list.** + +There are two options for deleting invalid email addresses: + +1) You can delete all invalid email addresses by setting `delete_all` to true in the request body. +2) You can delete some invalid email addresses by specifying certain addresses in an array in the request body. + +An invalid email occurs when you attempt to send email to an address that is formatted in a manner that does not meet internet email format standards or the email does not exist at the recipient's mail server. + +Examples include addresses without the @ sign or addresses that include certain special characters and/or spaces. This response can come from our own server or the recipient mail server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/invalid_emails.html). + +### DELETE /suppression/invalid_emails + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific invalid email + +**This endpoint allows you to retrieve a specific invalid email addresses.** + +An invalid email occurs when you attempt to send email to an address that is formatted in a manner that does not meet internet email format standards or the email does not exist at the recipient's mail server. + +Examples include addresses without the @ sign or addresses that include certain special characters and/or spaces. This response can come from our own server or the recipient mail server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/invalid_emails.html). + +### GET /suppression/invalid_emails/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a specific invalid email + +**This endpoint allows you to remove a specific email address from the invalid email address list.** + +An invalid email occurs when you attempt to send email to an address that is formatted in a manner that does not meet internet email format standards or the email does not exist at the recipient's mail server. + +Examples include addresses without the @ sign or addresses that include certain special characters and/or spaces. This response can come from our own server or the recipient mail server. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/invalid_emails.html). + +### DELETE /suppression/invalid_emails/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific spam report + +**This endpoint allows you to retrieve a specific spam report.** + +[Spam reports](https://sendgrid.com/docs/Glossary/spam_reports.html) happen when a recipient indicates that they think your email is [spam](https://sendgrid.com/docs/Glossary/spam.html) and then their email provider reports this to Twilio SendGrid. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/spam_reports.html). + +### GET /suppression/spam_report/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_report/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a specific spam report + +**This endpoint allows you to delete a specific spam report.** + +[Spam reports](https://sendgrid.com/docs/Glossary/spam_reports.html) happen when a recipient indicates that they think your email is [spam](https://sendgrid.com/docs/Glossary/spam.html) and then their email provider reports this to Twilio SendGrid. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/spam_reports.html). + +### DELETE /suppression/spam_report/{email} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_report/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all spam reports + +**This endpoint allows you to retrieve all spam reports.** + +[Spam reports](https://sendgrid.com/docs/Glossary/spam_reports.html) happen when a recipient indicates that they think your email is [spam](https://sendgrid.com/docs/Glossary/spam.html) and then their email provider reports this to Twilio SendGrid. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/spam_reports.html). + +### GET /suppression/spam_reports + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_reports"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete spam reports + +**This endpoint allows you to delete your spam reports.** + +There are two options for deleting spam reports: + +1) You can delete all spam reports by setting "delete_all" to true in the request body. +2) You can delete some spam reports by specifying the email addresses in an array in the request body. + +[Spam reports](https://sendgrid.com/docs/Glossary/spam_reports.html) happen when a recipient indicates that they think your email is [spam](https://sendgrid.com/docs/Glossary/spam.html) and then their email provider reports this to Twilio SendGrid. + +For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/spam_reports.html). + +### DELETE /suppression/spam_reports + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_reports"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all global suppressions + +**This endpoint allows you to retrieve a list of all email addresses that are globally suppressed.** + +A global suppression (or global unsubscribe) is an email address of a recipient who does not want to receive any of your messages. A globally suppressed recipient will be removed from any email you send. For more information, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Suppressions/global_unsubscribes.html). + +### GET /suppression/unsubscribes + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/unsubscribes"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# TEMPLATES + +## Create a transactional template. + +**This endpoint allows you to create a transactional template.** + +Each user can create up to 300 different transactional templates. Transactional templates are specific to accounts and subusers. Templates created on a parent account will not be accessible from the subuser accounts. + +Transactional templates are templates created specifically for transactional email and are not to be confused with [Marketing Campaigns templates](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/templates.html). For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +### POST /templates + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates"); + request.setBody("{\"name\":\"example_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all transactional templates. + +**This endpoint allows you to retrieve all transactional templates.** + +Each user can create up to 300 different transactional templates. Transactional templates are specific to accounts and subusers. Templates created on a parent account will not be accessible from the subuser accounts. + +Transactional templates are templates created specifically for transactional email and are not to be confused with [Marketing Campaigns templates](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/templates.html). For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +### GET /templates + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates"); + request.addQueryParam("generations", "legacy,dynamic") + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Edit a transactional template. + +**This endpoint allows you to edit a transactional template.** + +Each user can create up to 300 different transactional templates. Transactional templates are specific to accounts and subusers. Templates created on a parent account will not be accessible from the subuser accounts. + +Transactional templates are templates created specifically for transactional email and are not to be confused with [Marketing Campaigns templates](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/templates.html). For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + + +### PATCH /templates/{template_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}"); + request.setBody("{\"name\":\"new_example_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a single transactional template. + +**This endpoint allows you to retrieve a single transactional template.** + +Each user can create up to 300 different transactional templates. Transactional templates are specific to accounts and subusers. Templates created on a parent account will not be accessible from the subuser accounts. + +Transactional templates are templates created specifically for transactional email and are not to be confused with [Marketing Campaigns templates](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/templates.html). For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + + +### GET /templates/{template_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a template. + +**This endpoint allows you to delete a transactional template.** + +Each user can create up to 300 different transactional templates. Transactional templates are specific to accounts and subusers. Templates created on a parent account will not be accessible from the subuser accounts. + +Transactional templates are templates created specifically for transactional email and are not to be confused with [Marketing Campaigns templates](https://sendgrid.com/docs/User_Guide/Marketing_Campaigns/templates.html). For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + + +### DELETE /templates/{template_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create a new transactional template version. + +**This endpoint allows you to create a new version of a template.** + +Each transactional template can have multiple versions, each version with its own subject and content. Each user can have up to 300 versions across all templates. + +For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + + +### POST /templates/{template_id}/versions + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions"); + request.setBody("{\"name\":\"example_version_name\",\"html_content\":\"<%body%>\",\"plain_content\":\")<%body%>\",\"active\":1,\"template_id\":\"ddb96bbc-9b92-425e-8979-99464621b543\",\"subject\":\"<%subject%>\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Edit a transactional template version. + +**This endpoint allows you to edit a version of one of your transactional templates.** + +Each transactional template can have multiple versions, each version with its own subject and content. Each user can have up to 300 versions across all templates. + +For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| template_id | string | The ID of the original template | +| version_id | string | The ID of the template version | + +### PATCH /templates/{template_id}/versions/{version_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + request.setBody("{\"active\":1,\"html_content\":\"<%body%>\",\"subject\":\"<%subject%>\",\"name\":\"updated_example)_name\",\"plain_content\":\"<%body%>\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific transactional template version. + +**This endpoint allows you to retrieve a specific version of a template.** + +Each transactional template can have multiple versions, each version with its own subject and content. Each user can have up to 300 versions across all templates. + +For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| template_id | string | The ID of the original template | +| version_id | string | The ID of the template version | + +### GET /templates/{template_id}/versions/{version_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a transactional template version. + +**This endpoint allows you to delete one of your transactional template versions.** + +Each transactional template can have multiple versions, each version with its own subject and content. Each user can have up to 300 versions across all templates. + +For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| template_id | string | The ID of the original template | +| version_id | string | The ID of the template version | + +### DELETE /templates/{template_id}/versions/{version_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Activate a transactional template version. + +**This endpoint allows you to activate a version of one of your templates.** + +Each transactional template can have multiple versions, each version with its own subject and content. Each user can have up to 300 versions across across all templates. + + +For more information about transactional templates, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). + +## URI Parameters +| URI Parameter | Type | Description | +|---|---|---| +| template_id | string | The ID of the original template | +| version_id | string | The ID of the template version | + +### POST /templates/{template_id}/versions/{version_id}/activate + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions/{version_id}/activate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# TRACKING SETTINGS + +## Retrieve Tracking Settings + +**This endpoint allows you to retrieve a list of all tracking settings that you can enable on your account.** + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### GET /tracking_settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Click Tracking Settings + +**This endpoint allows you to change your current click tracking setting. You can enable, or disable, click tracking using this endpoint.** + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### PATCH /tracking_settings/click + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/click"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Click Track Settings + +**This endpoint allows you to retrieve your current click tracking setting.** + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### GET /tracking_settings/click + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/click"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Google Analytics Settings + +**This endpoint allows you to update your current setting for Google Analytics.** + +For more information about using Google Analytics, please refer to [Googles URL Builder](https://support.google.com/analytics/answer/1033867?hl=en) and their article on ["Best Practices for Campaign Building"](https://support.google.com/analytics/answer/1037445). + +We default the settings to Googles recommendations. For more information, see [Google Analytics Demystified](https://sendgrid.com/docs/Classroom/Track/Collecting_Data/google_analytics_demystified_ga_statistics_vs_sg_statistics.html). + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### PATCH /tracking_settings/google_analytics + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/google_analytics"); + request.setBody("{\"utm_campaign\":\"website\",\"utm_term\":\"\",\"utm_content\":\"\",\"enabled\":true,\"utm)_source\":\"sendgrid.com\",\"utm_medium\":\"email\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Google Analytics Settings + +**This endpoint allows you to retrieve your current setting for Google Analytics.** + +For more information about using Google Analytics, please refer to [Googles URL Builder](https://support.google.com/analytics/answer/1033867?hl=en) and their article on ["Best Practices for Campaign Building"](https://support.google.com/analytics/answer/1037445). + +We default the settings to Googles recommendations. For more information, see [Google Analytics Demystified](https://sendgrid.com/docs/Classroom/Track/Collecting_Data/google_analytics_demystified_ga_statistics_vs_sg_statistics.html). + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### GET /tracking_settings/google_analytics + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/google_analytics"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Open Tracking Settings + +**This endpoint allows you to update your current settings for open tracking.** + +Open Tracking adds an invisible image at the end of the email which can track email opens. If the email recipient has images enabled on their email client, a request to Twilio SendGrid's server for the invisible image is executed and an open event is logged. These events are logged in the Statistics portal, Email Activity interface, and are reported by the Event Webhook. + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### PATCH /tracking_settings/open + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/open"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Get Open Tracking Settings + +**This endpoint allows you to retrieve your current settings for open tracking.** + +Open Tracking adds an invisible image at the end of the email which can track email opens. If the email recipient has images enabled on their email client, a request to Twilio SendGrid's server for the invisible image is executed and an open event is logged. These events are logged in the Statistics portal, Email Activity interface, and are reported by the Event Webhook. + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### GET /tracking_settings/open + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/open"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Subscription Tracking Settings + +**This endpoint allows you to update your current settings for subscription tracking.** + +Subscription tracking adds links to the bottom of your emails that allows your recipients to subscribe to, or unsubscribe from, your emails. + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### PATCH /tracking_settings/subscription + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/subscription"); + request.setBody("{\"url\":\"url\",\"html_content\":\"html content\",\"enabled\":true,\"landing\":\"landing page) html\",\"replace\":\"replacement tag\",\"plain_content\":\"text content\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Subscription Tracking Settings + +**This endpoint allows you to retrieve your current settings for subscription tracking.** + +Subscription tracking adds links to the bottom of your emails that allows your recipients to subscribe to, or unsubscribe from, your emails. + +You can track a variety of the actions your recipients may take when interacting with your emails including opening your emails, clicking on links in your emails, and subscribing to (or unsubscribing from) your emails. + +For more information about tracking, please see our [User Guide](https://sendgrid.com/docs/User_Guide/Settings/tracking.html). + +### GET /tracking_settings/subscription + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/subscription"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` + +# USER + +## Get a user's account information. + +**This endpoint allows you to retrieve your user account details.** + +Your user's account information includes the user's account type and reputation. + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### GET /user/account + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/account"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve your credit balance + +**This endpoint allows you to retrieve the current credit balance for your account.** + +Your monthly credit allotment limits the number of emails you may send before incurring overage charges. For more information about credits and billing, please visit our [Classroom](https://sendgrid.com/docs/Classroom/Basics/Billing/billing_info_and_faqs.html). + +### GET /user/credits + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/credits"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update your account email address + +**This endpoint allows you to update the email address currently on file for your account.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### PUT /user/email + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/email"); + request.setBody("{\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve your account email address + +**This endpoint allows you to retrieve the email address currently on file for your account.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### GET /user/email + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/email"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update your password + +**This endpoint allows you to update your password.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### PUT /user/password + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/password"); + request.setBody("{\"new_password\":\"new_password\",\"old_password\":\"old_password\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a user's profile + +**This endpoint allows you to update your current profile details.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +It should be noted that any one or more of the parameters can be updated via the PATCH /user/profile endpoint. The only requirement is that you include at least one when you PATCH. + +### PATCH /user/profile + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/profile"); + request.setBody("{\"city\":\"Orange\",\"first_name\":\"Example\",\"last_name\":\"User\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Get a user's profile + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### GET /user/profile + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/profile"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Cancel or pause a scheduled send + +**This endpoint allows you to cancel or pause an email that has been scheduled to be sent.** + +If the maximum number of cancellations/pauses are added, HTTP 400 will +be returned. + +The Cancel Scheduled Sends feature allows the customer to cancel a scheduled send based on a Batch ID included in the SMTPAPI header.Scheduled sends canceled less than 10 minutes before the scheduled time are not guaranteed to be canceled. + +### POST /user/scheduled_sends + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/scheduled_sends"); + request.setBody("{\"batch_id\":\"YOUR_BATCH_ID\",\"status\":\"pause\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all scheduled sends + +**This endpoint allows you to retrieve all cancel/paused scheduled send information.** + +The Cancel Scheduled Sends feature allows the customer to cancel a scheduled send based on a Batch ID included in the SMTPAPI header.Scheduled sends canceled less than 10 minutes before the scheduled time are not guaranteed to be canceled. + +### GET /user/scheduled_sends + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update user scheduled send information + +**This endpoint allows you to update the status of a scheduled send for the given `batch_id`.** + +The Cancel Scheduled Sends feature allows the customer to cancel a scheduled send based on a Batch ID included in the SMTPAPI header.Scheduled sends canceled less than 10 minutes before the scheduled time are not guaranteed to be canceled. + +### PATCH /user/scheduled_sends/{batch_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + request.setBody("{\"status\":\"pause\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve scheduled send + +**This endpoint allows you to retrieve the cancel/paused scheduled send information for a specific `batch_id`.** + +The Cancel Scheduled Sends feature allows the customer to cancel a scheduled send based on a Batch ID included in the SMTPAPI header.Scheduled sends canceled less than 10 minutes before the scheduled time are not guaranteed to be canceled. + +### GET /user/scheduled_sends/{batch_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a cancellation or pause of a scheduled send + +**This endpoint allows you to delete the cancellation/pause of a scheduled send.** + +The Cancel Scheduled Sends feature allows the customer to cancel a scheduled send based on a Batch ID included in the SMTPAPI header.Scheduled sends cancelled less than 10 minutes before the scheduled time are not guaranteed to be cancelled. + +### DELETE /user/scheduled_sends/{batch_id} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Enforced TLS settings + +**This endpoint allows you to update your current Enforced TLS settings.** + +The Enforced TLS settings specify whether or not the recipient is required to support TLS or have a valid certificate. See the [SMTP Ports User Guide](https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/smtp_ports.html) for more information on opportunistic TLS. + +**Note:** If either setting is enabled and the recipient does not support TLS or have a valid certificate, we drop the message and send a block event with TLS required but not supported as the description. + +### PATCH /user/settings/enforced_tls + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/settings/enforced_tls"); + request.setBody("{\"require_tls\":true,\"require_valid_cert\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve current Enforced TLS settings. + +**This endpoint allows you to retrieve your current Enforced TLS settings.** + +The Enforced TLS settings specify whether or not the recipient is required to support TLS or have a valid certificate. See the [SMTP Ports User Guide](https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/smtp_ports.html) for more information on opportunistic TLS. + +**Note:** If either setting is enabled and the recipient does not support TLS or have a valid certificate, we drop the message and send a block event with TLS required but not supported as the description. + +### GET /user/settings/enforced_tls + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/settings/enforced_tls"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update your username + +**This endpoint allows you to update the username for your account.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### PUT /user/username + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/username"); + request.setBody("{\"username\":\"test_username\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve your username + +**This endpoint allows you to retrieve your current account username.** + +Keeping your user profile up to date is important. This will help Twilio SendGrid to verify who you are as well as contact you should we need to. + +For more information about your user profile: + +* [Twilio SendGrid Account Settings](https://sendgrid.com/docs/User_Guide/Settings/account.html) + +### GET /user/username + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/username"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update Event Notification Settings + +**This endpoint allows you to update your current event webhook settings.** + +If an event type is marked as `true`, then the event webhook will include information about that event. + +Twilio SendGrid's Event Webhook will notify a URL of your choice via HTTP POST with information about events that occur as Twilio SendGrid processes your email. + +Common uses of this data are to remove unsubscribes, react to spam reports, determine unengaged recipients, identify bounced email addresses, or create advanced analytics of your email program. + +### PATCH /user/webhooks/event/settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/event/settings"); + request.setBody("{\"group_resubscribe\":true,\"delivered\":true,\"group_unsubscribe\":true,\"spam_report\":true,\"url\":\"url\)",\"enabled\":true,\"bounce\":true,\"deferred\":true,\"unsubscribe\":true,\"dropped\":true,\"open\":true,\"click\":true,\"processed\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve Event Webhook settings + +**This endpoint allows you to retrieve your current event webhook settings.** + +If an event type is marked as `true`, then the event webhook will include information about that event. + +Twilio SendGrid's Event Webhook will notify a URL of your choice via HTTP POST with information about events that occur as Twilio SendGrid processes your email. + +Common uses of this data are to remove unsubscribes, react to spam reports, determine unengaged recipients, identify bounced email addresses, or create advanced analytics of your email program. + +### GET /user/webhooks/event/settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/event/settings"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Test Event Notification Settings + +**This endpoint allows you to test your event webhook by sending a fake event notification post to the provided URL.** + +Twilio SendGrid's Event Webhook will notify a URL of your choice via HTTP POST with information about events that occur as Twilio SendGrid processes your email. + +Common uses of this data are to remove unsubscribes, react to spam reports, determine unengaged recipients, identify bounced email addresses, or create advanced analytics of your email program. + +### POST /user/webhooks/event/test + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/event/test"); + request.setBody("{\"url\":\"url\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Create a parse setting + +**This endpoint allows you to create a new inbound parse setting.** + +The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content POSTed by Twilio SendGrid to a URL of your choosing. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Webhooks/parse.html). + +### POST /user/webhooks/parse/settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/parse/settings"); + request.setBody("{\"url\":\"http://email.myhosthame.com\",\"send_raw\":false,\"hostname\":\"myhostname.com\",\"spam)_check\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve all parse settings + +**This endpoint allows you to retrieve all of your current inbound parse settings.** + +The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content POSTed by Twilio SendGrid to a URL of your choosing. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Webhooks/parse.html). + +### GET /user/webhooks/parse/settings + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Update a parse setting + +**This endpoint allows you to update a specific inbound parse setting.** + +The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content POSTed by Twilio SendGrid to a URL of your choosing. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Webhooks/parse.html). + +### PATCH /user/webhooks/parse/settings/{hostname} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + request.setBody("{\"url\":\"http://newdomain.com/parse\",\"send_raw\":true,\"spam_check\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieve a specific parse setting + +**This endpoint allows you to retrieve a specific inbound parse setting.** + +The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content POSTed by Twilio SendGrid to a URL of your choosing. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Webhooks/parse.html). + +### GET /user/webhooks/parse/settings/{hostname} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Delete a parse setting + +**This endpoint allows you to delete a specific inbound parse setting.** + +The inbound parse webhook allows you to have incoming emails parsed, extracting some or all of the content, and then have that content POSTed by Twilio SendGrid to a URL of your choosing. For more information, please see our [User Guide](https://sendgrid.com/docs/API_Reference/Webhooks/parse.html). + +### DELETE /user/webhooks/parse/settings/{hostname} + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` +## Retrieves Inbound Parse Webhook statistics. + +**This endpoint allows you to retrieve the statistics for your Parse Webhook usage.** + +Twilio SendGrid's Inbound Parse Webhook allows you to parse the contents and attachments of incoming emails. The Parse API can then POST the parsed emails to a URL that you specify. The Inbound Parse Webhook cannot parse messages greater than 20MB in size, including all attachments. + +There are a number of pre-made integrations for the Twilio SendGrid Parse Webhook which make processing events easy. You can find these integrations in the [Library Index](https://sendgrid.com/docs/Integrate/libraries.html#-Webhook-Libraries). + +### GET /user/webhooks/parse/stats + + +```java + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } +``` diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 21756c0b..00000000 --- a/build.gradle +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Commands: - * - gradle build - * - gradle test - * - gradle assemble - * - gradle uploadArchives - * - * To execute the 'uploadArchives' task, the following properties must be specified - * in an external 'gradle.properties' file: - * - sonatypeUsername - * - sonatypePassword - */ - -apply plugin: 'java' -apply plugin: 'fatjar' -apply plugin: 'maven' -apply plugin: 'signing' - -group = 'com.sendgrid' -version = '2.2.2' -ext.packaging = 'jar' - -allprojects { - apply plugin: 'java' - sourceCompatibility = 1.6 - targetCompatibility = 1.6 -} - -if (!hasProperty("sonatypeUsername")) { - ext.sonatypeUsername = null - ext.sonatypePassword = null -} - -task wrapper(type: Wrapper) { - gradleVersion = '1.8' -} - -buildscript { - dependencies { - classpath 'eu.appsatori:gradle-fatjar-plugin:0.1.2' // adds fatJar task - } - repositories { - mavenCentral() - } -} - -dependencies { - compile 'com.sendgrid:smtpapi-java:1.2.0' - compile 'org.apache.httpcomponents:httpcore:4.3.2' - compile 'org.apache.httpcomponents:httpclient:4.3.4' - compile 'org.apache.httpcomponents:httpmime:4.3.4' - compile 'org.json:json:20140107' - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.skyscreamer', name: 'jsonassert', version: '1.2.3' -} - -repositories { - mavenCentral() -} - -allprojects { - gradle.projectsEvaluated { - tasks.withType(JavaCompile) { - options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" - } - } -} - -// adds 'with-dependencies' to the fatJar name -fatJar { - classifier 'jar' - baseName "sendgrid" - manifest { - attributes("Implementation-Title": "SendGrid", "Implementation-Version": version) - } -} - -// copy fatJar to base project directory so they will be in git (and on github for download) -build << { - copy { - println "Copying ${fatJar.archiveName} to $projectDir/repo/com/sendgrid/$version" - from("$buildDir/libs/${fatJar.archiveName}") - into("$projectDir/repo/com/sendgrid/$version") - } - copy { - println "Copying ${fatJar.archiveName} to $projectDir/repo/com/sendgrid" - from("$buildDir/libs/${fatJar.archiveName}") - into("$projectDir/repo/com/sendgrid") - } - tasks.renameSendGridVersionJarToSendGridJar.execute() -} - -task renameSendGridVersionJarToSendGridJar { - doLast { - file("$projectDir/repo/com/sendgrid/${fatJar.archiveName}").renameTo(file("$projectDir/repo/com/sendgrid/sendgrid-jar.jar")) - } -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from 'build/docs/javadoc' -} - -task sourcesJar(type: Jar) { - from sourceSets.main.allSource - classifier = 'sources' -} - -signing { - required { gradle.taskGraph.hasTask("uploadArchives") } - sign configurations.archives -} - -uploadArchives { - repositories { - mavenDeployer { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { - authentication(userName: sonatypeUsername, password: sonatypePassword) - } - - pom.project { - name 'sendgrid-java' - packaging 'jar' - description 'SendGrid Java helper library' - url 'https://github.com/sendgrid/sendgrid-java' - - scm { - url 'scm:git@github.com:sendgrid/sendgrid-java.git' - connection 'scm:git@github.com:sendgrid/sendgrid-java.git' - developerConnection 'scm:git@github.com:sendgrid/sendgrid-java.git' - } - - licenses { - license { - name 'MIT License' - url 'http://opensource.org/licenses/MIT' - distribution 'repo' - } - } - - developers { - developer { - id 'scottmotte' - name 'Scott Motte' - } - developer { - id 'elbou8' - name 'Yamil Asusta' - } - developer { - id 'eddiezane' - name 'Eddie Zaneski' - } - } - } - } - } -} - -artifacts { - archives fatJar - archives jar - archives javadocJar - archives sourcesJar -} diff --git a/examples/accesssettings/CreateAccessSettings.java b/examples/accesssettings/CreateAccessSettings.java new file mode 100644 index 00000000..6c98df1b --- /dev/null +++ b/examples/accesssettings/CreateAccessSettings.java @@ -0,0 +1,30 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/*Add one or more IPs to the whitelist +POST /access_settings/whitelist +*/ + +public class CreateAccessSettings extends Example { + + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ips\":[{\"ip\":\"192.168.1.1\"},{\"ip\":\"192.*.*.*\"},{\"ip\":\"192.168.1.3/32\"}]}"; + Request request = createRequest(Method.POST, endPoint, body); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + CreateAccessSettings createAccessSettings = new CreateAccessSettings(); + createAccessSettings.run(); + } +} diff --git a/examples/accesssettings/DeleteAccessSettings.java b/examples/accesssettings/DeleteAccessSettings.java new file mode 100644 index 00000000..a1abc860 --- /dev/null +++ b/examples/accesssettings/DeleteAccessSettings.java @@ -0,0 +1,30 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/* Remove one or more IPs from the whitelist + DELETE /access_settings/whitelist + */ + +public class DeleteAccessSettings extends Example { + + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ids\":[1,2,3]}"; + Request request = createRequest(Method.DELETE, endPoint, body); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + DeleteAccessSettings deleteAccessSettings = new DeleteAccessSettings(); + deleteAccessSettings.run(); + } +} \ No newline at end of file diff --git a/examples/accesssettings/DeleteIPFromAccessSettings.java b/examples/accesssettings/DeleteIPFromAccessSettings.java new file mode 100644 index 00000000..ce9eeb0c --- /dev/null +++ b/examples/accesssettings/DeleteIPFromAccessSettings.java @@ -0,0 +1,29 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/*Remove a specific IP from the whitelist +DELETE /access_settings/whitelist/{rule_id} +*/ + +public class DeleteIPFromAccessSettings extends Example { + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ids\":[1,2,3]}"; + Request request = createRequest(Method.DELETE, endPoint, body); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + DeleteIPFromAccessSettings deleteIPFromAccessSettings = new DeleteIPFromAccessSettings(); + deleteIPFromAccessSettings.run(); + } +} diff --git a/examples/accesssettings/Example.java b/examples/accesssettings/Example.java new file mode 100644 index 00000000..5de41ee0 --- /dev/null +++ b/examples/accesssettings/Example.java @@ -0,0 +1,31 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +public class Example { + + protected Request createRequest(Method method, String endPoint, String requestBody) { + Request request = new Request(); + request.setMethod(method); + request.setEndpoint(endPoint); + if (requestBody != null) { + request.setBody(requestBody); + } + return request; + } + + protected Response execute(Request request) throws IOException { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Response response = sg.api(request); + return response; + } + + protected void printResponseInfo(Response response) { + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } +} \ No newline at end of file diff --git a/examples/accesssettings/GetAccessSettings.java b/examples/accesssettings/GetAccessSettings.java new file mode 100644 index 00000000..24beee95 --- /dev/null +++ b/examples/accesssettings/GetAccessSettings.java @@ -0,0 +1,30 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/*Retrieve a list of currently whitelisted IPs +GET /access_settings/whitelist +*/ + +public class GetAccessSettings extends Example{ + + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ids\":[1,2,3]}"; + Request request = createRequest(Method.DELETE, endPoint, body); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + GetAccessSettings getAccessSettings = new GetAccessSettings(); + getAccessSettings.run(); + } +} \ No newline at end of file diff --git a/examples/accesssettings/GetAccessSettingsActivity.java b/examples/accesssettings/GetAccessSettingsActivity.java new file mode 100644 index 00000000..5ca02258 --- /dev/null +++ b/examples/accesssettings/GetAccessSettingsActivity.java @@ -0,0 +1,33 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/*Retrieve all recent access attempts +GET /access_settings/activity +*/ + +public class GetAccessSettingsActivity extends Example { + + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ids\":[1,2,3]}"; + Request request = createRequest(Method.DELETE, endPoint, body); + request.addQueryParam("limit", "1"); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + GetAccessSettingsActivity getAccessSettingsActivity = new GetAccessSettingsActivity(); + getAccessSettingsActivity.run(); + } +} + + diff --git a/examples/accesssettings/GetIPFromAccessSettings.java b/examples/accesssettings/GetIPFromAccessSettings.java new file mode 100644 index 00000000..456b141c --- /dev/null +++ b/examples/accesssettings/GetIPFromAccessSettings.java @@ -0,0 +1,30 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +/* Retrieve a specific whitelisted IP +GET /access_settings/whitelist/{rule_id} +*/ + +public class GetIPFromAccessSettings extends Example { + + private void run() throws IOException { + try { + String endPoint = "access_settings/whitelist"; + String body = "{\"ids\":[1,2,3]}"; + Request request = createRequest(Method.DELETE, endPoint, body); + Response response = execute(request); + printResponseInfo(response); + } catch (IOException ex) { + throw ex; + } + } + + public static void main(String[] args) throws IOException { + GetIPFromAccessSettings getIPFromAccessSettings = new GetIPFromAccessSettings(); + getIPFromAccessSettings.run(); + } +} \ No newline at end of file diff --git a/examples/accesssettings/README.md b/examples/accesssettings/README.md new file mode 100644 index 00000000..f68dc86f --- /dev/null +++ b/examples/accesssettings/README.md @@ -0,0 +1,10 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +This folder contains various examples on using the ACCESS_SETTINGS endpoint of SendGrid with Java: + +* [Retrieve a list of currently whitelisted IPs (GET /access_settings/whitelist)](GetAccessSettings.java) +* [Retrieve a specific whitelisted IP (GET /access_settings/whitelist/{rule_id})](GetIPFromAccessSettings.java) +* [Retrieve a list of currently whitelisted IPs (GET /access_settings/whitelist)](GetAccessSettingsActivity.java) +* [Remove a specific IP from the whitelist (DELETE /access_settings/whitelist/{rule_id}](DeleteIPFromAccessSettings.java) +* [Remove one or more IPs from the whitelist (DELETE /access_settings/whitelist)](DeleteAccessSettings.java) +* [Add one or more IPs to the whitelist (POST /access_settings/whitelist)](CreateAccessSettings.java) diff --git a/examples/alerts/alerts.java b/examples/alerts/alerts.java new file mode 100644 index 00000000..a364c464 --- /dev/null +++ b/examples/alerts/alerts.java @@ -0,0 +1,121 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a new Alert +// POST /alerts + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("alerts"); + request.setBody("{\"type\":\"stats_notification\",\"frequency\":\"daily\",\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all alerts +// GET /alerts + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update an alert +// PATCH /alerts/{alert_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("alerts/{alert_id}"); + request.setBody("{\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a specific alert +// GET /alerts/{alert_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete an alert +// DELETE /alerts/{alert_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/apikeys/apikeys.java b/examples/apikeys/apikeys.java new file mode 100644 index 00000000..d8e41909 --- /dev/null +++ b/examples/apikeys/apikeys.java @@ -0,0 +1,143 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Create API keys +// POST /api_keys + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("api_keys"); + request.setBody("{\"sample\":\"data\",\"scopes\":[\"mail.send\",\"alerts.create\",\"alerts.read\"],\"name\":\"My API Key\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all API Keys belonging to the authenticated user +// GET /api_keys + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update the name & scopes of an API Key +// PUT /api_keys/{api_key_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"scopes\":[\"user.profile.read\",\"user.profile.update\"],\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update API keys +// PATCH /api_keys/{api_key_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve an existing API Key +// GET /api_keys/{api_key_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete API keys +// DELETE /api_keys/{api_key_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/asm/asm.java b/examples/asm/asm.java new file mode 100644 index 00000000..a22c5100 --- /dev/null +++ b/examples/asm/asm.java @@ -0,0 +1,321 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Create a new suppression group +// POST /asm/groups + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups"); + request.setBody("{\"is_default\":true,\"description\":\"Suggestions for products our users might like.\",\"name\":\"Product Suggestions\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve information about multiple suppression groups +// GET /asm/groups + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups"); + request.addQueryParam("id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a suppression group. +// PATCH /asm/groups/{group_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("asm/groups/{group_id}"); + request.setBody("{\"description\":\"Suggestions for items our users might like.\",\"name\":\"Item Suggestions\",\"id\":103}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Get information on a single suppression group. +// GET /asm/groups/{group_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a suppression group. +// DELETE /asm/groups/{group_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Add suppressions to a suppression group +// POST /asm/groups/{group_id}/suppressions + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all suppressions for a suppression group +// GET /asm/groups/{group_id}/suppressions + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Search for suppressions within a group +// POST /asm/groups/{group_id}/suppressions/search + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions/search"); + request.setBody("{\"recipient_emails\":[\"exists1@example.com\",\"exists2@example.com\",\"doesnotexists@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a suppression from a suppression group +// DELETE /asm/groups/{group_id}/suppressions/{email} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}/suppressions/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all suppressions +// GET /asm/suppressions + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Add recipient addresses to the global suppression group. +// POST /asm/suppressions/global + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/suppressions/global"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a Global Suppression +// GET /asm/suppressions/global/{email} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Global Suppression +// DELETE /asm/suppressions/global/{email} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all suppression groups for an email address +// GET /asm/suppressions/{email} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/browsers/browsers.java b/examples/browsers/browsers.java new file mode 100644 index 00000000..a4eca365 --- /dev/null +++ b/examples/browsers/browsers.java @@ -0,0 +1,37 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics by browser. +// GET /browsers/stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("browsers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("browsers", "test_string"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("offset", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/campaigns/campaigns.java b/examples/campaigns/campaigns.java new file mode 100644 index 00000000..6345eca7 --- /dev/null +++ b/examples/campaigns/campaigns.java @@ -0,0 +1,258 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a Campaign +// POST /campaigns + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns"); + request.setBody("{\"custom_unsubscribe_url\":\"\",\"html_content\":\"

Check out our spring line!

\",\"list_ids\":[110,124],\"sender_id\":124451,\"subject\":\"New Products for Spring!\",\"plain_content\":\"Check out our spring line!\",\"suppression_group_id\":42,\"title\":\"March Newsletter\",\"segment_ids\":[110],\"categories\":[\"spring line\"],\"ip_pool\":\"marketing\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all Campaigns +// GET /campaigns + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a Campaign +// PATCH /campaigns/{campaign_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}"); + request.setBody("{\"html_content\":\"

Check out our summer line!

\",\"subject\":\"New Products for Summer!\",\"title\":\"May Newsletter\",\"categories\":[\"summer line\"],\"plain_content\":\"Check out our summer line!\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a single campaign +// GET /campaigns/{campaign_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Campaign +// DELETE /campaigns/{campaign_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a Scheduled Campaign +// PATCH /campaigns/{campaign_id}/schedules + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489451436}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Schedule a Campaign +// POST /campaigns/{campaign_id}/schedules + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489771528}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// View Scheduled Time of a Campaign +// GET /campaigns/{campaign_id}/schedules + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Unschedule a Scheduled Campaign +// DELETE /campaigns/{campaign_id}/schedules + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Send a Campaign +// POST /campaigns/{campaign_id}/schedules/now + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/now"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Send a Test Campaign +// POST /campaigns/{campaign_id}/schedules/test + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/test"); + request.setBody("{\"to\":\"your.email@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/categories/README.md b/examples/categories/README.md new file mode 100644 index 00000000..4ac50544 --- /dev/null +++ b/examples/categories/README.md @@ -0,0 +1,7 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +This folder contains various examples on using the Categories endpoint of SendGrid with Java: + +* [Retrieve all categories (GET /categories)](RetrieveAllCategories.java) +* [Retrieve Email Statistics for Categories (GET /categories/stats)](RetrieveStatisticsForCategories.java) +* [Retrieve sums of email stats for each category (GET /categories/stats/sums)](RetrieveSumsForCategories.java) \ No newline at end of file diff --git a/examples/categories/RetrieveAllCategories.java b/examples/categories/RetrieveAllCategories.java new file mode 100644 index 00000000..aa1ab2b6 --- /dev/null +++ b/examples/categories/RetrieveAllCategories.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all categories +// GET /categories + + +public class RetrieveAllCategories { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories"); + request.addQueryParam("category", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/categories/RetrieveStatisticsForCategories.java b/examples/categories/RetrieveStatisticsForCategories.java new file mode 100644 index 00000000..b02cf247 --- /dev/null +++ b/examples/categories/RetrieveStatisticsForCategories.java @@ -0,0 +1,36 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve Email Statistics for Categories +// GET /categories/stats + + +public class RetrieveMailStatisticsForCategories { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("categories", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/categories/RetrieveSumsForCategories.java b/examples/categories/RetrieveSumsForCategories.java new file mode 100644 index 00000000..a82e8e2d --- /dev/null +++ b/examples/categories/RetrieveSumsForCategories.java @@ -0,0 +1,38 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve sums of email stats for each category [Needs: Stats object defined, has category ID?] +// GET /categories/stats/sums + + +public class RetrieveSumsForCategories { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/clients/GetEmailStatistics.java b/examples/clients/GetEmailStatistics.java new file mode 100644 index 00000000..632c817c --- /dev/null +++ b/examples/clients/GetEmailStatistics.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics by client type. +// GET /clients/stats + +public class GetEmailStatistics { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/clients/GetEmailStatisticsByClientType.java b/examples/clients/GetEmailStatisticsByClientType.java new file mode 100644 index 00000000..eef0e2a2 --- /dev/null +++ b/examples/clients/GetEmailStatisticsByClientType.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve stats by a specific client type. +// GET /clients/{client_type}/stats + +public class GetEmailStatisticsByClientType { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/{client_type}/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/clients/README.md b/examples/clients/README.md new file mode 100644 index 00000000..0c74bd24 --- /dev/null +++ b/examples/clients/README.md @@ -0,0 +1,6 @@ +![SendGrid Logo](https://github.com/sendgrid/sendgrid-java/blob/main/twilio_sendgrid_logo.png) + +This folder contains various examples on using the CLIENTS endpoint of SendGrid with Java: + +* [Retrieve email statistics by client type (GET /clients/stats)](GetEmailStatistics.java) +* [Retrieve stats by a specific client type (GET /clients/{client_type}/stats)](GetEmailStatisticsByClientType.java) diff --git a/examples/contactdb/customfields.java b/examples/contactdb/customfields.java new file mode 100644 index 00000000..e4ce5c58 --- /dev/null +++ b/examples/contactdb/customfields.java @@ -0,0 +1,97 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a Custom Field +// POST /contactdb/custom_fields + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/custom_fields"); + request.setBody("{\"type\":\"text\",\"name\":\"pet\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all custom fields +// GET /contactdb/custom_fields + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a Custom Field +// GET /contactdb/custom_fields/{custom_field_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Custom Field +// DELETE /contactdb/custom_fields/{custom_field_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/contactdb/listrecipients.java b/examples/contactdb/listrecipients.java new file mode 100644 index 00000000..cfe621e7 --- /dev/null +++ b/examples/contactdb/listrecipients.java @@ -0,0 +1,102 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Add Multiple Recipients to a List +// POST /contactdb/lists/{list_id}/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all recipients on a List +// GET /contactdb/lists/{list_id}/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Add a Single Recipient to a List +// POST /contactdb/lists/{list_id}/recipients/{recipient_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Single Recipient from a Single List +// DELETE /contactdb/lists/{list_id}/recipients/{recipient_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + request.addQueryParam("recipient_id", "1"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/contactdb/lists.java b/examples/contactdb/lists.java new file mode 100644 index 00000000..1e55fd29 --- /dev/null +++ b/examples/contactdb/lists.java @@ -0,0 +1,146 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a List +// POST /contactdb/lists + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists"); + request.setBody("{\"name\":\"your list name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all lists +// GET /contactdb/lists + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete Multiple lists +// DELETE /contactdb/lists + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists"); + request.setBody("[1,2,3,4]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a List +// PATCH /contactdb/lists/{list_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/lists/{list_id}"); + request.setBody("{\"name\":\"newlistname\"}"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a single list +// GET /contactdb/lists/{list_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a List +// DELETE /contactdb/lists/{list_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/contactdb/recipients.java b/examples/contactdb/recipients.java new file mode 100644 index 00000000..ebba8d90 --- /dev/null +++ b/examples/contactdb/recipients.java @@ -0,0 +1,234 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Update Recipient +// PATCH /contactdb/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"first_name\":\"Guy\",\"last_name\":\"Jones\",\"email\":\"jones@example.com\"}]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Add recipients +// POST /contactdb/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"age\":25,\"last_name\":\"User\",\"email\":\"example@example.com\",\"first_name\":\"\"},{\"age\":25,\"last_name\":\"User\",\"email\":\"example2@example.com\",\"first_name\":\"Example\"}]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve recipients +// GET /contactdb/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete Recipient +// DELETE /contactdb/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve the count of billable recipients +// GET /contactdb/recipients/billable_count + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/billable_count"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a Count of Recipients +// GET /contactdb/recipients/count + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/count"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve recipients matching search criteria +// GET /contactdb/recipients/search + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/search"); + request.addQueryParam("{field_name}", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a single recipient +// GET /contactdb/recipients/{recipient_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Recipient +// DELETE /contactdb/recipients/{recipient_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve the lists that a recipient is on +// GET /contactdb/recipients/{recipient_id}/lists + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}/lists"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/contactdb/reservedfields.java b/examples/contactdb/reservedfields.java new file mode 100644 index 00000000..e9ceafa9 --- /dev/null +++ b/examples/contactdb/reservedfields.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve reserved fields +// GET /contactdb/reserved_fields + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/reserved_fields"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/contactdb/segments.java b/examples/contactdb/segments.java new file mode 100644 index 00000000..84c60027 --- /dev/null +++ b/examples/contactdb/segments.java @@ -0,0 +1,147 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a Segment +// POST /contactdb/segments + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/segments"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and_or\":\"\",\"value\":\"Miller\"},{\"operator\":\"gt\",\"field\":\"last_clicked\",\"and_or\":\"and\",\"value\":\"01/02/2015\"},{\"operator\":\"eq\",\"field\":\"clicks.campaign_identifier\",\"and_or\":\"or\",\"value\":\"513\"}],\"name\":\"Last Name Miller\",\"list_id\":4}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all segments +// GET /contactdb/segments + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a segment +// PATCH /contactdb/segments/{segment_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and_or\":\"\",\"value\":\"Miller\"}],\"name\":\"The Millers\",\"list_id\":5}"); + request.addQueryParam("segment_id", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a segment +// GET /contactdb/segments/{segment_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("segment_id", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a segment +// DELETE /contactdb/segments/{segment_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve recipients on a segment +// GET /contactdb/segments/{segment_id}/recipients + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/dataresidency/setregion.java b/examples/dataresidency/setregion.java new file mode 100644 index 00000000..5dc42150 --- /dev/null +++ b/examples/dataresidency/setregion.java @@ -0,0 +1,77 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Set data residency to navigate to a region/edge. +// Currently supported: "global", "eu" + + +public class Example { + public static void main(String[] args) throws IOException { + try { + + final Mail helloWorld = buildHelloEmail(); + + Request request = new Request(); + request.setEndpoint("mail/send"); + request.setBody(helloWorld.build()); + request.setMethod(Method.POST); + + // sending to global data residency + Sendgrid sg = buildSendgridObj("global"); + Response response = sg.api(request); + System.out.println("Sending to hostname: " + sg.getHost()); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + + // sending to EU data residency + Sendgrid sg = buildSendgridObj("eu"); + Response response = sg.api(request); + System.out.println("Sending to hostname: " + sg.getHost()); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + + // not configuring any region defaults to global + Sendgrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Response response = sg.api(request); + System.out.println("Sending to hostname: " + sg.getHost()); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + + } catch (IOException ex) { + throw ex; + } + } + + public static Mail buildHelloEmail() { + Email from = new Email("test@example.com"); + String subject = "Hello World from the Twilio SendGrid Java Library"; + Email to = new Email("test@example.com"); + Content content = new Content("text/plain", "some text here"); + // Note that when you use this constructor an initial personalization object + // is created for you. It can be accessed via + // mail.personalization.get(0) as it is a List object + Mail mail = new Mail(from, subject, to, content); + Email email = new Email("test2@example.com"); + mail.personalization.get(0).addTo(email); + + return mail; + } + + public static Sendgrid buildSendgridObj(String region){ + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + sg.setDataResidency(region); + return sg; + + } +} + diff --git a/examples/dependencies/jackson-annotations-2.7.0.jar b/examples/dependencies/jackson-annotations-2.7.0.jar new file mode 100644 index 00000000..96fb17cf Binary files /dev/null and b/examples/dependencies/jackson-annotations-2.7.0.jar differ diff --git a/examples/dependencies/jackson-core-2.7.3.jar b/examples/dependencies/jackson-core-2.7.3.jar new file mode 100644 index 00000000..9b20cee6 Binary files /dev/null and b/examples/dependencies/jackson-core-2.7.3.jar differ diff --git a/examples/dependencies/jackson-databind-2.7.3.jar b/examples/dependencies/jackson-databind-2.7.3.jar new file mode 100644 index 00000000..29d90afe Binary files /dev/null and b/examples/dependencies/jackson-databind-2.7.3.jar differ diff --git a/examples/devices/devices.java b/examples/devices/devices.java new file mode 100644 index 00000000..7c253eac --- /dev/null +++ b/examples/devices/devices.java @@ -0,0 +1,36 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics by device type. +// GET /devices/stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("devices/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/dropbox/UploadToDropBox.java b/examples/dropbox/UploadToDropBox.java new file mode 100644 index 00000000..1d729cd1 --- /dev/null +++ b/examples/dropbox/UploadToDropBox.java @@ -0,0 +1,62 @@ +package dropbox; + +import com.dropbox.core.DbxRequestConfig; +import com.dropbox.core.v2.DbxClientV2; +import com.dropbox.core.v2.files.FileMetadata; +import com.sendgrid.Attachments; +import org.apache.commons.codec.binary.Base64; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.Charset; + +/* + Add Dropbox dependencies for compiling code + Gradle : compile 'com.dropbox.core:dropbox-core-sdk:3.0.5' + maven : + + com.dropbox.core + dropbox-core-sdk + 3.0.5 + + */ +public class UploadToDropBox { + public static void main(String[] args) { + String fileName = "book3.txt"; + String type = "text/plain"; + String content = "This test checks if the builder works fine"; + InputStream contentStream = new ByteArrayInputStream(content.getBytes(Charset.forName("UTF-8"))); + String contentId = "someId"; + String dispositon = "someDisposition"; + String accessToken = "user's access token"; + String path = "/path/to/folder"; + + Attachments attachments = new Attachments.Builder(fileName, contentStream) + .withType(type) + .withContentId(contentId) + .withDisposition(dispositon) + .build(); + String returnPath = uploadToDropbox(attachments, accessToken, path); + System.out.println("Path: " + returnPath); + } + + /** + * Uploads attachment to Dropbox + * + * @param attachments attachment to be uploaded + * @param accessToken user's Dropbox access token + * @param path path of the folder in which attachment needs to be added. Should not end with / + * @return the full path to the uploaded file + */ + private static String uploadToDropbox(Attachments attachments, String accessToken, String path) { + try { + DbxRequestConfig config = DbxRequestConfig.newBuilder("sendgrid/0.1").build(); + DbxClientV2 client = new DbxClientV2(config, accessToken); + FileMetadata uploadedFile = client.files().upload(String.format("%s/%s", path, attachments.getFilename())) + .uploadAndFinish(new ByteArrayInputStream((Base64.decodeBase64(attachments.getContent())))); + return uploadedFile.getPathDisplay(); + } catch (Exception ex) { + throw new RuntimeException("Error while uploading to Dropbox", ex); + } + } +} diff --git a/examples/geo/geo.java b/examples/geo/geo.java new file mode 100644 index 00000000..6b74fda9 --- /dev/null +++ b/examples/geo/geo.java @@ -0,0 +1,37 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics by country and state/province. +// GET /geo/stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("geo/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("country", "US"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/helpers/eventwebhook/Example.java b/examples/helpers/eventwebhook/Example.java new file mode 100644 index 00000000..6077736a --- /dev/null +++ b/examples/helpers/eventwebhook/Example.java @@ -0,0 +1,49 @@ +import com.sendgrid.helpers.eventwebhook.EventWebhook; +import com.sendgrid.helpers.eventwebhook.EventWebhookHeader; +import com.twilio.security.RequestValidator; +import com.twilio.twiml.MessagingResponse; +import com.twilio.twiml.messaging.Body; +import com.twilio.twiml.messaging.Message; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import spark.Route; + +import java.security.Security; +import java.security.interfaces.ECPublicKey; +import java.util.HashMap; +import java.util.Map; + +import static spark.Spark.post; + +public class Example { + public static void main(String[] args) { + Security.addProvider(new BouncyCastleProvider()); + + final Route webhookHandler = (req, res) -> { + try { + final String publicKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE83T4O/n84iotIvIW4mdBgQ/7dAfSmpqIM8kF9mN1flpVKS3GRqe62gw+2fNNRaINXvVpiglSI8eNEc6wEA3F+g=="; + + final String signature = req.headers(EventWebhookHeader.SIGNATURE.toString()); + final String timestamp = req.headers(EventWebhookHeader.TIMESTAMP.toString()); + final byte[] requestBody = req.bodyAsBytes(); + + final EventWebhook ew = new EventWebhook(); + final ECPublicKey ellipticCurvePublicKey = ew.ConvertPublicKeyToECDSA(publicKey); + final boolean valid = ew.VerifySignature(ellipticCurvePublicKey, requestBody, signature, timestamp); + System.out.println("Valid Signature: " + valid); + + if (valid) { + res.status(204); + } else { + res.status(403); + } + + return null; + } catch (final Exception exception) { + res.status(500); + return exception.toString(); + } + }; + + post("/sendgrid/webhook", webhookHandler); + } +} diff --git a/examples/helpers/mail/Example.java b/examples/helpers/mail/Example.java new file mode 100644 index 00000000..174e38ba --- /dev/null +++ b/examples/helpers/mail/Example.java @@ -0,0 +1,279 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; +import com.sendgrid.helpers.mail.Mail; +import com.sendgrid.helpers.mail.objects.*; + +import java.io.IOException; + +public class Example { + + // Fully populated Mail object + public static Mail buildKitchenSink() { + Mail mail = new Mail(); + + Email fromEmail = new Email(); + fromEmail.setName("Example User"); + fromEmail.setEmail("test@example.com"); + mail.setFrom(fromEmail); + + mail.setSubject("Hello World from the Twilio SendGrid Java Library"); + + Personalization personalization = new Personalization(); + Email to = new Email(); + to.setName("Example User"); + to.setEmail("test1@example.com"); + personalization.addTo(to); + to.setName("Example User"); + to.setEmail("test2@example.com"); + personalization.addTo(to); + Email cc = new Email(); + cc.setName("Example User"); + cc.setEmail("test3@example.com"); + personalization.addCc(cc); + cc.setName("Example User"); + cc.setEmail("test4@example.com"); + personalization.addCc(cc); + Email bcc = new Email(); + bcc.setName("Example User"); + bcc.setEmail("test5@example.com"); + personalization.addBcc(bcc); + bcc.setName("Example User"); + bcc.setEmail("test6@example.com"); + personalization.addBcc(bcc); + personalization.setSubject("Hello World from the Personalized Twilio SendGrid Java Library"); + personalization.addHeader("X-Test", "test"); + personalization.addHeader("X-Mock", "true"); + personalization.addSubstitution("%name%", "Example User"); + personalization.addSubstitution("%city%", "Riverside"); + personalization.addCustomArg("user_id", "343"); + personalization.addCustomArg("type", "marketing"); + personalization.setSendAt(1443636843); + mail.addPersonalization(personalization); + + Personalization personalization2 = new Personalization(); + Email to2 = new Email(); + to2.setName("Example User"); + to2.setEmail("test1@example.com"); + personalization2.addTo(to2); + Email fromEmail2 = new Email(); + fromEmail2.setName("Example User"); + fromEmail2.setEmail("test2@example.com"); + personalization2.setFrom(fromEmail2); + to2.setName("Example User"); + to2.setEmail("test3@example.com"); + personalization2.addTo(to2); + Email cc2 = new Email(); + cc2.setName("Example User"); + cc2.setEmail("test4@example.com"); + personalization2.addCc(cc2); + cc2.setName("Example User"); + cc2.setEmail("test5@example.com"); + personalization2.addCc(cc2); + Email bcc2 = new Email(); + bcc2.setName("Example User"); + bcc2.setEmail("test6@example.com"); + personalization2.addBcc(bcc2); + bcc2.setName("Example User"); + bcc2.setEmail("test7@example.com"); + personalization2.addBcc(bcc2); + personalization2.setSubject("Hello World from the Personalized Twilio SendGrid Java Library"); + personalization2.addHeader("X-Test", "test"); + personalization2.addHeader("X-Mock", "true"); + personalization2.addSubstitution("%name%", "Example User"); + personalization2.addSubstitution("%city%", "Denver"); + personalization2.addCustomArg("user_id", "343"); + personalization2.addCustomArg("type", "marketing"); + personalization2.setSendAt(1443636843); + mail.addPersonalization(personalization2); + + Content content = new Content(); + content.setType("text/plain"); + content.setValue("some text here"); + mail.addContent(content); + content.setType("text/html"); + content.setValue("some text here"); + mail.addContent(content); + + Attachments attachments = new Attachments(); + attachments.setContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"); + attachments.setType("application/pdf"); + attachments.setFilename("balance_001.pdf"); + attachments.setDisposition("attachment"); + attachments.setContentId("Balance Sheet"); + mail.addAttachments(attachments); + + Attachments attachments2 = new Attachments(); + attachments2.setContent("BwdW"); + attachments2.setType("image/png"); + attachments2.setFilename("banner.png"); + attachments2.setDisposition("inline"); + attachments2.setContentId("Banner"); + mail.addAttachments(attachments2); + + mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + + mail.addSection("%section1%", "Substitution Text for Section 1"); + mail.addSection("%section2%", "Substitution Text for Section 2"); + + mail.addHeader("X-Test1", "1"); + mail.addHeader("X-Test2", "2"); + + mail.addCategory("May"); + mail.addCategory("2016"); + + mail.addCustomArg("campaign", "welcome"); + mail.addCustomArg("weekday", "morning"); + + mail.setSendAt(1443636842); + + ASM asm = new ASM(); + asm.setGroupId(99); + asm.setGroupsToDisplay(new int[]{4, 5, 6, 7, 8}); + mail.setASM(asm); + + // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work + // mail.setBatchId("sendgrid_batch_id"); + + mail.setIpPoolId("23"); + + MailSettings mailSettings = new MailSettings(); + BccSettings bccSettings = new BccSettings(); + bccSettings.setEnable(true); + bccSettings.setEmail("test@example.com"); + mailSettings.setBccSettings(bccSettings); + Setting sandBoxMode = new Setting(); + sandBoxMode.setEnable(true); + mailSettings.setSandboxMode(sandBoxMode); + Setting bypassListManagement = new Setting(); + bypassListManagement.setEnable(true); + mailSettings.setBypassListManagement(bypassListManagement); + // Note: Bypass Spam, Bounce, and Unsubscribe management cannot + // be combined with Bypass List Management + Setting bypassSpamManagement = new Setting(); + bypassSpamManagement.setEnable(true); + mailSettings.setBypassSpamManagement(bypassSpamManagement); + Setting bypassBounceManagement = new Setting(); + bypassBounceManagement.setEnable(true); + mailSettings.setBypassBounceManagement(bypassBounceManagement); + Setting bypassUnsubscribeManagement = new Setting(); + bypassUnsubscribeManagement.setEnable(true); + mailSettings.setBypassUnsubscribeManagement(bypassUnsubscribeManagement); + FooterSetting footerSetting = new FooterSetting(); + footerSetting.setEnable(true); + footerSetting.setText("Footer Text"); + footerSetting.setHtml("Footer Text"); + mailSettings.setFooterSetting(footerSetting); + SpamCheckSetting spamCheckSetting = new SpamCheckSetting(); + spamCheckSetting.setEnable(true); + spamCheckSetting.setSpamThreshold(1); + spamCheckSetting.setPostToUrl("https://spamcatcher.sendgrid.com"); + mailSettings.setSpamCheckSetting(spamCheckSetting); + mail.setMailSettings(mailSettings); + + TrackingSettings trackingSettings = new TrackingSettings(); + ClickTrackingSetting clickTrackingSetting = new ClickTrackingSetting(); + clickTrackingSetting.setEnable(true); + clickTrackingSetting.setEnableText(true); + trackingSettings.setClickTrackingSetting(clickTrackingSetting); + OpenTrackingSetting openTrackingSetting = new OpenTrackingSetting(); + openTrackingSetting.setEnable(true); + openTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + trackingSettings.setOpenTrackingSetting(openTrackingSetting); + SubscriptionTrackingSetting subscriptionTrackingSetting = new SubscriptionTrackingSetting(); + subscriptionTrackingSetting.setEnable(true); + subscriptionTrackingSetting.setText("text to insert into the text/plain portion of the message"); + subscriptionTrackingSetting.setHtml("html to insert into the text/html portion of the message"); + subscriptionTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + trackingSettings.setSubscriptionTrackingSetting(subscriptionTrackingSetting); + GoogleAnalyticsSetting googleAnalyticsSetting = new GoogleAnalyticsSetting(); + googleAnalyticsSetting.setEnable(true); + googleAnalyticsSetting.setCampaignSource("some source"); + googleAnalyticsSetting.setCampaignTerm("some term"); + googleAnalyticsSetting.setCampaignContent("some content"); + googleAnalyticsSetting.setCampaignName("some name"); + googleAnalyticsSetting.setCampaignMedium("some medium"); + trackingSettings.setGoogleAnalyticsSetting(googleAnalyticsSetting); + mail.setTrackingSettings(trackingSettings); + + Email replyTo = new Email(); + replyTo.setName("Example User"); + replyTo.setEmail("test@example.com"); + mail.setReplyTo(replyTo); + + return mail; + } + + // API V3 Dynamic Template implementation + public static Mail buildDynamicTemplate() { + Mail mail = new Mail(); + + Email fromEmail = new Email(); + fromEmail.setName("Example User"); + fromEmail.setEmail("test@example.com"); + mail.setFrom(fromEmail); + + mail.setTemplateId("d-c6dcf1f72bdd4beeb15a9aa6c72fcd2c"); + + Personalization personalization = new Personalization(); + personalization.addDynamicTemplateData("name", "Example User"); + personalization.addDynamicTemplateData("city", "Denver"); + personalization.addTo(new Email("test@example.com")); + mail.addPersonalization(personalization); + + return mail; + } + + // Minimum required to send an email + public static Mail buildHelloEmail() { + Email from = new Email("test@example.com"); + String subject = "Hello World from the Twilio SendGrid Java Library"; + Email to = new Email("test@example.com"); + Content content = new Content("text/plain", "some text here"); + // Note that when you use this constructor an initial personalization object + // is created for you. It can be accessed via + // mail.personalization.get(0) as it is a List object + Mail mail = new Mail(from, subject, to, content); + Email email = new Email("test2@example.com"); + mail.personalization.get(0).addTo(email); + + return mail; + } + + public static void baselineExample() throws IOException { + final Mail helloWorld = buildHelloEmail(); + send(helloWorld); + } + + public static void kitchenSinkExample() throws IOException { + final Mail kitchenSink = buildKitchenSink(); + send(kitchenSink); + } + + public static void dynamicTemplateExample() throws IOException { + final Mail dynamicTemplate = buildDynamicTemplate(); + send(dynamicTemplate); + } + + private static void send(final Mail mail) throws IOException { + final SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + sg.addRequestHeader("X-Mock", "true"); + + final Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + + final Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } + + public static void main(String[] args) throws IOException { + baselineExample(); + kitchenSinkExample(); + dynamicTemplateExample(); + } +} diff --git a/examples/helpers/mail/MultipleEmailsMultipleRecipients.java b/examples/helpers/mail/MultipleEmailsMultipleRecipients.java new file mode 100644 index 00000000..e96fca16 --- /dev/null +++ b/examples/helpers/mail/MultipleEmailsMultipleRecipients.java @@ -0,0 +1,55 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; +import com.sendgrid.helpers.mail.Mail; +import com.sendgrid.helpers.mail.objects.Content; +import com.sendgrid.helpers.mail.objects.Email; +import com.sendgrid.helpers.mail.objects.Personalization; + +import java.io.IOException; + +public class MultipleEmailsMultipleRecipients { + + public static void main(String[] args) throws IOException { + final Mail mail = new Mail(); + + mail.setFrom(new Email("test@example.com", "Example User")); + mail.setSubject("Sending with Twilio SendGrid is Fun"); + + // Details on how to send an email with dynamic transactional templates: + // https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/ + mail.setTemplateId("d-12345678901234567890123456789012"); + + final Personalization personalization1 = new Personalization(); + personalization1.addTo(new Email("test1@example.com", "Example User1")); + personalization1.addDynamicTemplateData("name", "Example User1"); + personalization1.addDynamicTemplateData("city", "Denver"); + mail.addPersonalization(personalization1); + + final Personalization personalization2 = new Personalization(); + personalization2.addTo(new Email("test2@example.com", "Example User2")); + personalization2.setFrom(new Email("test3@example.com", "Example User3")); + personalization2.addDynamicTemplateData("name", "Example User2"); + personalization2.addDynamicTemplateData("city", "San Francisco"); + mail.addPersonalization(personalization2); + + mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java")); + mail.addContent(new Content("text/html", "and easy to do anywhere, even with Java")); + + send(mail); + } + + private static void send(final Mail mail) throws IOException { + final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY")); + final Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + + final Response response = client.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } +} diff --git a/examples/helpers/mail/SingleEmailMultipleRecipients.java b/examples/helpers/mail/SingleEmailMultipleRecipients.java new file mode 100644 index 00000000..8829124f --- /dev/null +++ b/examples/helpers/mail/SingleEmailMultipleRecipients.java @@ -0,0 +1,44 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; +import com.sendgrid.helpers.mail.Mail; +import com.sendgrid.helpers.mail.objects.Content; +import com.sendgrid.helpers.mail.objects.Email; +import com.sendgrid.helpers.mail.objects.Personalization; + +import java.io.IOException; + +public class SingleEmailMultipleRecipients { + + public static void main(String[] args) throws IOException { + final Mail mail = new Mail(); + + mail.setFrom(new Email("test@example.com", "Example User")); + mail.setSubject("Sending with Twilio SendGrid is Fun"); + + final Personalization personalization = new Personalization(); + personalization.addTo(new Email("test1@example.com", "Example User1")); + personalization.addTo(new Email("test2@example.com", "Example User2")); + personalization.addTo(new Email("test3@example.com", "Example User3")); + mail.addPersonalization(personalization); + + mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java")); + mail.addContent(new Content("text/html", "and easy to do anywhere, even with Java")); + + send(mail); + } + + private static void send(final Mail mail) throws IOException { + final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY")); + final Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + + final Response response = client.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } +} diff --git a/examples/ips/AddToPool.java b/examples/ips/AddToPool.java new file mode 100644 index 00000000..01e6b16b --- /dev/null +++ b/examples/ips/AddToPool.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Add an IP address to a pool +// POST /ips/pools/{pool_name}/ips + + +public class AddIPToPool { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools/{pool_name}/ips"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/AddToWarmup.java b/examples/ips/AddToWarmup.java new file mode 100644 index 00000000..89ebaad1 --- /dev/null +++ b/examples/ips/AddToWarmup.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + + +////////////////////////////////////////////////////////////////// +// Add an IP to warmup +// POST /ips/warmup + + +public class AddIPToWarmup { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/warmup"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/CreatePool.java b/examples/ips/CreatePool.java new file mode 100644 index 00000000..c91d82f0 --- /dev/null +++ b/examples/ips/CreatePool.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Create an IP pool. +// POST /ips/pools + + +public class CreateIPPool { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools"); + request.setBody("{\"name\":\"marketing\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/DeletePool.java b/examples/ips/DeletePool.java new file mode 100644 index 00000000..51c50249 --- /dev/null +++ b/examples/ips/DeletePool.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Delete an IP pool. +// DELETE /ips/pools/{pool_name} + + +public class DeletePool { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/README.md b/examples/ips/README.md new file mode 100644 index 00000000..7ded4310 --- /dev/null +++ b/examples/ips/README.md @@ -0,0 +1,18 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +This folder contains various examples on using the IPs endpoint of SendGrid with Java: + +* [Retrieve all IP addresses (GET /ips)](RetrieveAllIPs.java) +* [Retrieve all assigned IPs (GET /ips/assigned)](RetrieveAssignedIPs.java) +* [Create an IP pool (POST /ips/pools)](CreatePool.java) +* [Retrieve all IP pools (GET /ips/pools)](RetrieveAllPools.java) +* [Update an IP pools name (PUT /ips/pools/{pool_name})](UpdatePoolName.java) +* [Retrieve all IPs in a specified pool (GET /ips/pools/{pool_name})](RetrieveIPsInPool.java) +* [Delete an IP pool. (DELETE /ips/pools/{pool_name})](DeletePool.java) +* [Add an IP address to a pool (POST /ips/pools/{pool_name}/ips)](AddToPool.java) +* [Remove an IP address from a pool (DELETE /ips/pools/{pool_name}/ips/{ip}](RemoveFromPool.java) +* [Add an IP to warmup (POST /ips/warmup)](AddToWarmup.java) +* [Retrieve all IPs currently in warmup (GET /ips/warmup)](RetrieveIPsInWarmup.java) +* [Retrieve warmup status for a specific IP address (GET /ips/warmup/{ip_address})](RetrieveWarmupStatus.java) +* [Remove an IP from warmup (DELETE /ips/warmup/{ip_address})](RemoveFromWarmup.java) +* [Retrieve all IP pools an IP address belongs to (GET /ips/{ip_address})](RetrievePoolsForIP.java) \ No newline at end of file diff --git a/examples/ips/RemoveFromPool.java b/examples/ips/RemoveFromPool.java new file mode 100644 index 00000000..ceb5f2be --- /dev/null +++ b/examples/ips/RemoveFromPool.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Remove an IP address from a pool. +// DELETE /ips/pools/{pool_name}/ips/{ip} + + +public class RemoveIPFromPool { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}/ips/{ip}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RemoveFromWarmup.java b/examples/ips/RemoveFromWarmup.java new file mode 100644 index 00000000..b99229de --- /dev/null +++ b/examples/ips/RemoveFromWarmup.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + + +////////////////////////////////////////////////////////////////// +// Remove an IP from warmup +// DELETE /ips/warmup/{ip_address} + + +public class RemoveFromWarmup { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RetrieveAllIPs.java b/examples/ips/RetrieveAllIPs.java new file mode 100644 index 00000000..14845939 --- /dev/null +++ b/examples/ips/RetrieveAllIPs.java @@ -0,0 +1,34 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + + +////////////////////////////////////////////////////////////////// +// Retrieve all IP addresses +// GET /ips + + +public class RetrieveAllIPs { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("exclude_whitelabels", "true"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RetrieveAllPools.java b/examples/ips/RetrieveAllPools.java new file mode 100644 index 00000000..c6734071 --- /dev/null +++ b/examples/ips/RetrieveAllPools.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve all IP pools. +// GET /ips/pools + + +public class RetrieveAllIPPools { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/ips/RetrieveAssignedIPs.java b/examples/ips/RetrieveAssignedIPs.java new file mode 100644 index 00000000..968834cc --- /dev/null +++ b/examples/ips/RetrieveAssignedIPs.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve all assigned IPs +// GET /ips/assigned + + +public class RetrieveAllAssignedIPs { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/assigned"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RetrieveIPsInPool.java b/examples/ips/RetrieveIPsInPool.java new file mode 100644 index 00000000..72330c3f --- /dev/null +++ b/examples/ips/RetrieveIPsInPool.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve all IPs in a specified pool. +// GET /ips/pools/{pool_name} + + +public class RetrieveIPsInPool { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RetrieveIPsInWarmup.java b/examples/ips/RetrieveIPsInWarmup.java new file mode 100644 index 00000000..3767656b --- /dev/null +++ b/examples/ips/RetrieveIPsInWarmup.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + + +////////////////////////////////////////////////////////////////// +// Retrieve all IPs currently in warmup +// GET /ips/warmup + + +public class RetrieveIPsInWarmup { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/RetrievePoolsForIP.java b/examples/ips/RetrievePoolsForIP.java new file mode 100644 index 00000000..8f19b7a7 --- /dev/null +++ b/examples/ips/RetrievePoolsForIP.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + + +////////////////////////////////////////////////////////////////// +// Retrieve all IP pools an IP address belongs to +// GET /ips/{ip_address} + + +public class RetrieveAllPoolsForIP { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/ips/RetrieveWarmupStatus.java b/examples/ips/RetrieveWarmupStatus.java new file mode 100644 index 00000000..5d315b8f --- /dev/null +++ b/examples/ips/RetrieveWarmupStatus.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + + +////////////////////////////////////////////////////////////////// +// Retrieve warmup status for a specific IP address +// GET /ips/warmup/{ip_address} + + +public class RetrieveIPsWarmupStatus { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/ips/UpdatePoolName.java b/examples/ips/UpdatePoolName.java new file mode 100644 index 00000000..4e9c2a26 --- /dev/null +++ b/examples/ips/UpdatePoolName.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Update an IP pools name. +// PUT /ips/pools/{pool_name} + + +public class UpdateIPPoolName { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("ips/pools/{pool_name}"); + request.setBody("{\"name\":\"new_pool_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mail/mail.java b/examples/mail/mail.java new file mode 100644 index 00000000..ada390c2 --- /dev/null +++ b/examples/mail/mail.java @@ -0,0 +1,77 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a batch ID +// POST /mail/batch + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/batch"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Validate batch ID +// GET /mail/batch/{batch_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail/batch/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// v3 Mail Send +// POST /mail/send + +// This endpoint has a helper, check it out [here](https://github.com/sendgrid/sendgrid-java/blob/HEAD/src/main/java/com/sendgrid/helpers/README.md). + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\"[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"from\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"attachments\":[{\"name\":\"file1\",\"filename\":\"file1.jpg\",\"content\":\"[BASE64 encoded content block here]\",\"disposition\":\"inline\",\"content_id\":\"ii_139db99fdb5c3704\",\"type\":\"jpg\"}],\"personalizations\":[{\"to\":[{\"email\":\"john.doe@example.com\",\"name\":\"John Doe\"}],\"cc\":[{\"email\":\"jane.doe@example.com\",\"name\":\"Jane Doe\"}],\"bcc\":[{\"email\":\"sam.doe@example.com\",\"name\":\"Sam Doe\"}],\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\"[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"headers\":{\"X-Accept-Language\":\"en\",\"X-Mailer\":\"MyApp\"},\"send_at\":1409348513,\"substitutions\":{\"type\":\"object\",\"id\":\"substitutions\"},\"subject\":\"Hello, World!\"}],\"subject\":\"Hello, World!\",\"ip_pool_name\":\"[YOUR POOL NAME GOES HERE]\",\"content\":[{\"type\":\"text/html\",\"value\":\"

Hello, world!

\"}],\"headers\":{},\"asm\":{\"groups_to_display\":[1,2,3],\"group_id\":1},\"batch_id\":\"[YOUR BATCH ID GOES HERE]\",\"tracking_settings\":{\"subscription_tracking\":{\"text\":\"If you would like to unsubscribe and stop receiveing these emails <% click here %>.\",\"enable\":true,\"html\":\"If you would like to unsubscribe and stop receiving these emails <% clickhere %>.\",\"substitution_tag\":\"<%click here%>\"},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"%opentrack\"},\"click_tracking\":{\"enable\":true,\"enable_text\":true},\"ganalytics\":{\"utm_campaign\":\"[NAME OF YOUR REFERRER SOURCE]\",\"enable\":true,\"utm_name\":\"[NAME OF YOUR CAMPAIGN]\",\"utm_term\":\"[IDENTIFY PAID KEYWORDS HERE]\",\"utm_content\":\"[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]\",\"utm_medium\":\"[NAME OF YOUR MARKETING MEDIUM e.g. email]\"}},\"mail_settings\":{\"footer\":{\"text\":\"Thanks,/n The Twilio SendGrid Team\",\"enable\":true,\"html\":\"

Thanks
The Twilio SendGrid Team

\"},\"spam_check\":{\"threshold\":3,\"post_to_url\":\"http://example.com/compliance\",\"enable\":true},\"bypass_list_management\":{\"enable\":true},\"sandbox_mode\":{\"enable\":false},\"bcc\":{\"enable\":true,\"email\":\"ben.doe@example.com\"}},\"reply_to\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"sections\":{\"section\":{\":sectionName2\":\"section 2 text\",\":sectionName1\":\"section 1 text\"}},\"template_id\":\"[YOUR TEMPLATE ID GOES HERE]\",\"categories\":[\"category1\",\"category2\"],\"send_at\":1409348513}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/mailboxproviders/mailboxproviders.java b/examples/mailboxproviders/mailboxproviders.java new file mode 100644 index 00000000..4e0c6a06 --- /dev/null +++ b/examples/mailboxproviders/mailboxproviders.java @@ -0,0 +1,37 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics by mailbox provider. +// GET /mailbox_providers/stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mailbox_providers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("mailbox_providers", "test_string"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/mailsettings/GetAddressWhitelistMailSettings.java b/examples/mailsettings/GetAddressWhitelistMailSettings.java new file mode 100644 index 00000000..fdc81c1b --- /dev/null +++ b/examples/mailsettings/GetAddressWhitelistMailSettings.java @@ -0,0 +1,28 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Retrieve address whitelist mail settings +// GET /mail_settings/address_whitelist + + +public class GetAddressWhitelistMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/address_whitelist"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetAllMailSettings.java b/examples/mailsettings/GetAllMailSettings.java new file mode 100644 index 00000000..e85b6e48 --- /dev/null +++ b/examples/mailsettings/GetAllMailSettings.java @@ -0,0 +1,30 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Retrieve all mail settings +// GET /mail_settings + + +public class GetAllMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/mailsettings/GetBCCMailSettings.java b/examples/mailsettings/GetBCCMailSettings.java new file mode 100644 index 00000000..90ab31d9 --- /dev/null +++ b/examples/mailsettings/GetBCCMailSettings.java @@ -0,0 +1,28 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Retrieve all BCC mail settings +// GET /mail_settings/bcc + + +public class GetBCCMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bcc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetBouncePurgeMailSettings.java b/examples/mailsettings/GetBouncePurgeMailSettings.java new file mode 100644 index 00000000..2f390764 --- /dev/null +++ b/examples/mailsettings/GetBouncePurgeMailSettings.java @@ -0,0 +1,28 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Retrieve bounce purge mail settings +// GET /mail_settings/bounce_purge + + +public class GetBouncePurgeMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bounce_purge"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetFooterMailSettings.java b/examples/mailsettings/GetFooterMailSettings.java new file mode 100644 index 00000000..bea04d0b --- /dev/null +++ b/examples/mailsettings/GetFooterMailSettings.java @@ -0,0 +1,31 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Retrieve footer mail settings +// GET /mail_settings/footer + + +public class GetFooterMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/footer"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetForwardBounceMailSettings.java b/examples/mailsettings/GetForwardBounceMailSettings.java new file mode 100644 index 00000000..33331585 --- /dev/null +++ b/examples/mailsettings/GetForwardBounceMailSettings.java @@ -0,0 +1,31 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Retrieve forward bounce mail settings +// GET /mail_settings/forward_bounce + + +public class GetForwardBounceMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_bounce"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetForwardSpamMailSettings.java b/examples/mailsettings/GetForwardSpamMailSettings.java new file mode 100644 index 00000000..0b890294 --- /dev/null +++ b/examples/mailsettings/GetForwardSpamMailSettings.java @@ -0,0 +1,28 @@ +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import java.io.IOException; + +////////////////////////////////////////////////////////////////// +// Retrieve forward spam mail settings +// GET /mail_settings/forward_spam + + +public class GetForwardSpamMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_spam"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetPlainContentMailSettings.java b/examples/mailsettings/GetPlainContentMailSettings.java new file mode 100644 index 00000000..38f7cfe4 --- /dev/null +++ b/examples/mailsettings/GetPlainContentMailSettings.java @@ -0,0 +1,28 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Retrieve plain content mail settings +// GET /mail_settings/plain_content + + +public class GetPlainContentMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/plain_content"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetSpamCheckMailSettings.java b/examples/mailsettings/GetSpamCheckMailSettings.java new file mode 100644 index 00000000..9460cac0 --- /dev/null +++ b/examples/mailsettings/GetSpamCheckMailSettings.java @@ -0,0 +1,28 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Retrieve spam check mail settings +// GET /mail_settings/spam_check + + +public class GetSpamCheckMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/spam_check"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/GetTemplateMailSettings.java b/examples/mailsettings/GetTemplateMailSettings.java new file mode 100644 index 00000000..8b648be4 --- /dev/null +++ b/examples/mailsettings/GetTemplateMailSettings.java @@ -0,0 +1,28 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Retrieve legacy template mail settings +// GET /mail_settings/template + + +public class GetTemplateMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/template"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/README.md b/examples/mailsettings/README.md new file mode 100644 index 00000000..34e83317 --- /dev/null +++ b/examples/mailsettings/README.md @@ -0,0 +1,23 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +This folder contains various examples on using the Mail Settings endpoint of SendGrid with Java: + +* [Retrieve all mail settings (GET /mail_settings)](GetAllMailSettings.java) +* [Retrieve address whitelist mail settings (GET /mail_settings/address_whitelist)](GetAddressWhitelistMailSettings.java) +* [Retrieve all BCC mail settings (GET /mail_settings/bcc)](GetBCCMailSettings.java) +* [Retrieve bounce purge mail settings (GET /mail_settings/bounce_purge)](GetBouncePurgeMailSettings.java) +* [Retrieve footer mail settings (GET /mail_settings/footer)](GetFooterMailSettings.java) +* [Retrieve forward bounce mail settings (GET /mail_settings/forward_bounce)](GetForwardBounceMailSettings.java) +* [Retrieve forward spam mail settings (GET /mail_settings/forward_spam)](GetForwardSpamMailSettings.java) +* [Retrieve plain content mail settings (GET /mail_settings/plain_content)](GetPlainContentMailSettings.java) +* [Retrieve spam check mail settings (GET /mail_settings/spam_check)](GetSpamCheckMailSettings.java) +* [Retrieve legacy template mail settings (GET /mail_settings/template)](GetTemplateMailSettings.java) +* [Update address whitelist mail settings (PATCH /mail_settings/address_whitelist)](UpdateAddressWhitelist.java) +* [Update BCC mail settings (PATCH /mail_settings/bcc)](UpdateBCCMailSettings.java) +* [Update bounce purge mail settings (PATCH /mail_settings/bounce_purge)](UpdateBouncePurgeMailSettings.java) +* [Update footer mail settings (PATCH /mail_settings/footer)](UpdateFooterMailSettings.java) +* [Update forward bounce mail settings (PATCH /mail_settings/forward_bounce)](UpdateForwardBounceMailSettings.java) +* [Update forward spam mail settings (PATCH /mail_settings/forward_spam)](UpdateForwardSpamMailSettings.java) +* [Update plain content mail settings (PATCH /mail_settings/plain_content)](UpdatePlainContentMailSettings.java) +* [Update spam check mail settings (PATCH /mail_settings/spam_check)](UpdateSpamCheckMailSettings.java) +* [Update template mail settings (PATCH /mail_settings/template)](UpdateTemplateMailSettings.java) diff --git a/examples/mailsettings/UpdateAddressWhitelist.java b/examples/mailsettings/UpdateAddressWhitelist.java new file mode 100644 index 00000000..db58c282 --- /dev/null +++ b/examples/mailsettings/UpdateAddressWhitelist.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update address whitelist mail settings +// PATCH /mail_settings/address_whitelist + + +public class UpdateAddressWhitelist { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/address_whitelist"); + request.setBody("{\"list\":[\"email1@example.com\",\"example.com\"],\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateBCCMailSettings.java b/examples/mailsettings/UpdateBCCMailSettings.java new file mode 100644 index 00000000..33faba1a --- /dev/null +++ b/examples/mailsettings/UpdateBCCMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update BCC mail settings +// PATCH /mail_settings/bcc + + +public class UpdateBCCMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bcc"); + request.setBody("{\"enabled\":false,\"email\":\"email@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateBouncePurgeMailSettings.java b/examples/mailsettings/UpdateBouncePurgeMailSettings.java new file mode 100644 index 00000000..83a53e10 --- /dev/null +++ b/examples/mailsettings/UpdateBouncePurgeMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update bounce purge mail settings +// PATCH /mail_settings/bounce_purge + + +public class UpdateBouncePurgeMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bounce_purge"); + request.setBody("{\"hard_bounces\":5,\"soft_bounces\":5,\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateFooterMailSettings.java b/examples/mailsettings/UpdateFooterMailSettings.java new file mode 100644 index 00000000..fedf35b0 --- /dev/null +++ b/examples/mailsettings/UpdateFooterMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update footer mail settings +// PATCH /mail_settings/footer + + +public class UpdateFooterMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/footer"); + request.setBody("{\"html_content\":\"...\",\"enabled\":true,\"plain_content\":\"...\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateForwardBounceMailSettings.java b/examples/mailsettings/UpdateForwardBounceMailSettings.java new file mode 100644 index 00000000..677b94e9 --- /dev/null +++ b/examples/mailsettings/UpdateForwardBounceMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update forward bounce mail settings +// PATCH /mail_settings/forward_bounce + + +public class UpdateForwardBounceMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_bounce"); + request.setBody("{\"enabled\":true,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateForwardSpamMailSettings.java b/examples/mailsettings/UpdateForwardSpamMailSettings.java new file mode 100644 index 00000000..3b27f353 --- /dev/null +++ b/examples/mailsettings/UpdateForwardSpamMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update forward spam mail settings +// PATCH /mail_settings/forward_spam + + +public class UpdateForwardSpamMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_spam"); + request.setBody("{\"enabled\":false,\"email\":\"\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdatePlainContentMailSettings.java b/examples/mailsettings/UpdatePlainContentMailSettings.java new file mode 100644 index 00000000..4cb680f5 --- /dev/null +++ b/examples/mailsettings/UpdatePlainContentMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update plain content mail settings +// PATCH /mail_settings/plain_content + + +public class UpdatePlainContentMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/plain_content"); + request.setBody("{\"enabled\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateSpamCheckMailSettings.java b/examples/mailsettings/UpdateSpamCheckMailSettings.java new file mode 100644 index 00000000..e7cf8dc2 --- /dev/null +++ b/examples/mailsettings/UpdateSpamCheckMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update spam check mail settings +// PATCH /mail_settings/spam_check + + +public class UpdateSpamCheckMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/spam_check"); + request.setBody("{\"url\":\"url\",\"max_score\":5,\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/mailsettings/UpdateTemplateMailSettings.java b/examples/mailsettings/UpdateTemplateMailSettings.java new file mode 100644 index 00000000..57e1b22a --- /dev/null +++ b/examples/mailsettings/UpdateTemplateMailSettings.java @@ -0,0 +1,29 @@ +import java.io.IOException; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +////////////////////////////////////////////////////////////////// +// Update template mail settings +// PATCH /mail_settings/template + + +public class UpdateTemplateMailSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/template"); + request.setBody("{\"html_content\":\"<% body %>\",\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/partnersettings/partnersettings.java b/examples/partnersettings/partnersettings.java new file mode 100644 index 00000000..b4364bb9 --- /dev/null +++ b/examples/partnersettings/partnersettings.java @@ -0,0 +1,78 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Returns a list of all partner settings. +// GET /partner_settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Updates New Relic partner settings. +// PATCH /partner_settings/new_relic + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("partner_settings/new_relic"); + request.setBody("{\"enable_subuser_statistics\":true,\"enabled\":true,\"license_key\":\"\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Returns all New Relic partner settings. +// GET /partner_settings/new_relic + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings/new_relic"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/scopes/scopes.java b/examples/scopes/scopes.java new file mode 100644 index 00000000..69d2db5d --- /dev/null +++ b/examples/scopes/scopes.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve a list of scopes for which this user has access. +// GET /scopes + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("scopes"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/senderauthentication/domains.java b/examples/senderauthentication/domains.java new file mode 100644 index 00000000..2ffe0a7e --- /dev/null +++ b/examples/senderauthentication/domains.java @@ -0,0 +1,281 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a domain authorization. +// POST /whitelabel/domains + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains"); + request.setBody("{\"automatic_security\":false,\"username\":\"john@example.com\",\"domain\":\"example.com\",\"default\":true,\"custom_spf\":true,\"ips\":[\"192.168.1.1\",\"192.168.1.2\"],\"subdomain\":\"news\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// List all domain authorization. +// GET /whitelabel/domains + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("domain", "test_string"); + request.addQueryParam("exclude_subusers", "true"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Get the default domain authorization. +// GET /whitelabel/domains/default + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/default"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// List the domain authorization associated with the given user. +// GET /whitelabel/domains/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Disassociate a domain authorization from a given user. +// DELETE /whitelabel/domains/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a domain authorization. +// PATCH /whitelabel/domains/{domain_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/domains/{domain_id}"); + request.setBody("{\"default\":false,\"custom_spf\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a domain authorization. +// GET /whitelabel/domains/{domain_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a domain authorization. +// DELETE /whitelabel/domains/{domain_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Associate a domain authorization with a given user. +// POST /whitelabel/domains/{domain_id}/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{domain_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Add an IP to a domain authorization. +// POST /whitelabel/domains/{id}/ips + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/ips"); + request.setBody("{\"ip\":\"192.168.0.1\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Remove an IP from a domain authorization. +// DELETE /whitelabel/domains/{id}/ips/{ip} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{id}/ips/{ip}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Validate a domain authorization. +// POST /whitelabel/domains/{id}/validate + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/senderauthentication/ips.java b/examples/senderauthentication/ips.java new file mode 100644 index 00000000..c1983608 --- /dev/null +++ b/examples/senderauthentication/ips.java @@ -0,0 +1,127 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class CommonExample { + protected SendGrid sg; + protected Request request; + + protected static void init() { + this.sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + this.request = new Request(); + } +} + +////////////////////////////////////////////////////////////////// +// Create a reverse DNS record +// POST /whitelabel/ips + + +public class Example extends CommonExample { + public static void main(String[] args) throws IOException { + try { + init(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips"); + request.setBody("{\"ip\":\"192.168.1.1\",\"domain\":\"example.com\",\"subdomain\":\"email\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all reverse DNS records +// GET /whitelabel/ips + + +public class Example extends CommonExample { + public static void main(String[] args) throws IOException { + try { + init(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a reverse DNS record +// GET /whitelabel/ips/{id} + + +public class Example extends CommonExample { + public static void main(String[] args) throws IOException { + try { + init(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a reverse DNS record +// DELETE /whitelabel/ips/{id} + + +public class Example extends CommonExample { + public static void main(String[] args) throws IOException { + try { + init(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Validate a reverse DNS record +// POST /whitelabel/ips/{id}/validate + + +public class Example extends CommonExample { + public static void main(String[] args) throws IOException { + try { + init(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/senderauthentication/links.java b/examples/senderauthentication/links.java new file mode 100644 index 00000000..bf661339 --- /dev/null +++ b/examples/senderauthentication/links.java @@ -0,0 +1,238 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a Branded Link +// POST /whitelabel/links + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links"); + request.setBody("{\"default\":true,\"domain\":\"example.com\",\"subdomain\":\"mail\"}"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all link Branding +// GET /whitelabel/links + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a Default Link Branding +// GET /whitelabel/links/default + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/default"); + request.addQueryParam("domain", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve Associated Link Branding +// GET /whitelabel/links/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Disassociate a Link Branding +// DELETE /whitelabel/links/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a Link Branding +// PATCH /whitelabel/links/{id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/links/{id}"); + request.setBody("{\"default\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a Link Branding +// GET /whitelabel/links/{id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Link Branding +// DELETE /whitelabel/links/{id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Validate a Link Branding +// POST /whitelabel/links/{id}/validate + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{id}/validate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Associate a Link Branding +// POST /whitelabel/links/{link_id}/subuser + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{link_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/senders/senders.java b/examples/senders/senders.java new file mode 100644 index 00000000..d81630da --- /dev/null +++ b/examples/senders/senders.java @@ -0,0 +1,143 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a Sender Identity +// POST /senders + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Get all Sender Identities +// GET /senders + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update a Sender Identity +// PATCH /senders/{sender_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("senders/{sender_id}"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// View a Sender Identity +// GET /senders/{sender_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a Sender Identity +// DELETE /senders/{sender_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Resend Sender Identity Verification +// POST /senders/{sender_id}/resend_verification + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders/{sender_id}/resend_verification"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/stats/stats.java b/examples/stats/stats.java new file mode 100644 index 00000000..1dbe5c25 --- /dev/null +++ b/examples/stats/stats.java @@ -0,0 +1,36 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve global email statistics +// GET /stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/subusers/CreateMonitorSettings.java b/examples/subusers/CreateMonitorSettings.java new file mode 100644 index 00000000..6fecfaff --- /dev/null +++ b/examples/subusers/CreateMonitorSettings.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create monitor settings +// POST /subusers/{subuser_name}/monitor + + +public class CreateMonitorSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":50000,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/CreateSubUser.java b/examples/subusers/CreateSubUser.java new file mode 100644 index 00000000..9cb283c8 --- /dev/null +++ b/examples/subusers/CreateSubUser.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create Subuser +// POST /subusers + + +public class CreateSubUser { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers"); + request.setBody("{\"username\":\"John@example.com\",\"ips\":[\"1.1.1.1\",\"2.2.2.2\"],\"password\":\"johns_password\",\"email\":\"John@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/DeleteMonitorSettings.java b/examples/subusers/DeleteMonitorSettings.java new file mode 100644 index 00000000..ffcc25c8 --- /dev/null +++ b/examples/subusers/DeleteMonitorSettings.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Delete monitor settings +// DELETE /subusers/{subuser_name}/monitor + + +public class DeleteMonitorSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/DeleteSubUser.java b/examples/subusers/DeleteSubUser.java new file mode 100644 index 00000000..68207edf --- /dev/null +++ b/examples/subusers/DeleteSubUser.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete a subuser +// DELETE /subusers/{subuser_name} + + +public class DeleteSubUser { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/EnableOrDisableUser.java b/examples/subusers/EnableOrDisableUser.java new file mode 100644 index 00000000..107b7def --- /dev/null +++ b/examples/subusers/EnableOrDisableUser.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Enable/disable a subuser +// PATCH /subusers/{subuser_name} + + +public class EnableOrDisableUser { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("subusers/{subuser_name}"); + request.setBody("{\"disabled\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/ListAllSubUsers.java b/examples/subusers/ListAllSubUsers.java new file mode 100644 index 00000000..ebc408f3 --- /dev/null +++ b/examples/subusers/ListAllSubUsers.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// List all Subusers +// GET /subusers + +public class ListAllSubUsers { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/RetrieveEmailStatistics.java b/examples/subusers/RetrieveEmailStatistics.java new file mode 100644 index 00000000..479f4f2e --- /dev/null +++ b/examples/subusers/RetrieveEmailStatistics.java @@ -0,0 +1,37 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve email statistics for your subusers. +// GET /subusers/stats + + +public class RetrieveEmailStatistics { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("subusers", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/subusers/RetrieveMonitorSettings.java b/examples/subusers/RetrieveMonitorSettings.java new file mode 100644 index 00000000..6d219e2f --- /dev/null +++ b/examples/subusers/RetrieveMonitorSettings.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve monitor settings for a subuser +// GET /subusers/{subuser_name}/monitor + + +public class RetrieveMonitorSettings { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/RetrieveMonthlyEmailStatistics.java b/examples/subusers/RetrieveMonthlyEmailStatistics.java new file mode 100644 index 00000000..b7d1c9b2 --- /dev/null +++ b/examples/subusers/RetrieveMonthlyEmailStatistics.java @@ -0,0 +1,36 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve the monthly email statistics for a single subuser +// GET /subusers/{subuser_name}/stats/monthly + + +public class RetrieveMonthlyEmailStatistics { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/stats/monthly"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/RetrieveMonthlyStats.java b/examples/subusers/RetrieveMonthlyStats.java new file mode 100644 index 00000000..7310c072 --- /dev/null +++ b/examples/subusers/RetrieveMonthlyStats.java @@ -0,0 +1,36 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve monthly stats for all subusers +// GET /subusers/stats/monthly + + +public class RetrieveMonthlyStats { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/monthly"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/subusers/RetrieveSubUserReputation.java b/examples/subusers/RetrieveSubUserReputation.java new file mode 100644 index 00000000..18664ed2 --- /dev/null +++ b/examples/subusers/RetrieveSubUserReputation.java @@ -0,0 +1,32 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +////////////////////////////////////////////////////////////////// +// Retrieve Subuser Reputations +// GET /subusers/reputations + + +public class RetrieveSubUserReputation { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/reputations"); + request.addQueryParam("usernames", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/subusers/RetrieveTotalsForEachEmail.java b/examples/subusers/RetrieveTotalsForEachEmail.java new file mode 100644 index 00000000..de741967 --- /dev/null +++ b/examples/subusers/RetrieveTotalsForEachEmail.java @@ -0,0 +1,37 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve the totals for each email statistic metric for all subusers. +// GET /subusers/stats/sums + + +public class RetrieveTotalsForEachEmail { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/UpdateAssignedIPs.java b/examples/subusers/UpdateAssignedIPs.java new file mode 100644 index 00000000..60479769 --- /dev/null +++ b/examples/subusers/UpdateAssignedIPs.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Update IPs assigned to a subuser +// PUT /subusers/{subuser_name}/ips + + +public class UpdateAssignedIps { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/ips"); + request.setBody("[\"127.0.0.1\"]"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/subusers/UpdateMonitorSettings.java b/examples/subusers/UpdateMonitorSettings.java new file mode 100644 index 00000000..81567982 --- /dev/null +++ b/examples/subusers/UpdateMonitorSettings.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Update Monitor Settings for a subuser +// PUT /subusers/{subuser_name}/monitor + + +public class UpdateMonitorSetting { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":500,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteBlocks.java b/examples/suppression/DeleteBlocks.java new file mode 100644 index 00000000..484ddc67 --- /dev/null +++ b/examples/suppression/DeleteBlocks.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete blocks +// DELETE /suppression/blocks + +public class DeleteBlocks { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteBounce.java b/examples/suppression/DeleteBounce.java new file mode 100644 index 00000000..a8a9270d --- /dev/null +++ b/examples/suppression/DeleteBounce.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete a bounce +// DELETE /suppression/bounces/{email} + +public class DeleteBounce { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces/{email}"); + request.addQueryParam("email_address", "example@example.com"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteBounces.java b/examples/suppression/DeleteBounces.java new file mode 100644 index 00000000..ec286aec --- /dev/null +++ b/examples/suppression/DeleteBounces.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete bounces +// DELETE /suppression/bounces + +public class DeleteBounces { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces"); + request.setBody("{\"emails\":[\"example@example.com\",\"example2@example.com\"],\"delete_all\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteInvalidEmails.java b/examples/suppression/DeleteInvalidEmails.java new file mode 100644 index 00000000..56e3e25e --- /dev/null +++ b/examples/suppression/DeleteInvalidEmails.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete invalid emails +// DELETE /suppression/invalid_emails + +public class DeleteInvalidEmails { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteSpamReports.java b/examples/suppression/DeleteSpamReports.java new file mode 100644 index 00000000..c4adb4b3 --- /dev/null +++ b/examples/suppression/DeleteSpamReports.java @@ -0,0 +1,30 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete spam reports +// DELETE /suppression/spam_reports + +public class DeleteSpamReports { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_reports"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteSpecificBlock.java b/examples/suppression/DeleteSpecificBlock.java new file mode 100644 index 00000000..4e252c3f --- /dev/null +++ b/examples/suppression/DeleteSpecificBlock.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete a specific block +// DELETE /suppression/blocks/{email} + +public class DeleteSpecificBlock { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteSpecificInvalidEmail.java b/examples/suppression/DeleteSpecificInvalidEmail.java new file mode 100644 index 00000000..03def455 --- /dev/null +++ b/examples/suppression/DeleteSpecificInvalidEmail.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete a specific invalid email +// DELETE /suppression/invalid_emails/{email} + +public class DeleteSpecificInvalidEmail { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/DeleteSpecificSpamReport.java b/examples/suppression/DeleteSpecificSpamReport.java new file mode 100644 index 00000000..fcad75bf --- /dev/null +++ b/examples/suppression/DeleteSpecificSpamReport.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Delete a specific spam report +// DELETE /suppression/spam_report/{email} + +public class DeleteSpecificSpamReport { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_report/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetAllBlocks.java b/examples/suppression/GetAllBlocks.java new file mode 100644 index 00000000..c653c9be --- /dev/null +++ b/examples/suppression/GetAllBlocks.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all blocks +// GET /suppression/blocks + +public class GetAllBlocks { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetAllBounces.java b/examples/suppression/GetAllBounces.java new file mode 100644 index 00000000..6c98010d --- /dev/null +++ b/examples/suppression/GetAllBounces.java @@ -0,0 +1,31 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all bounces +// GET /suppression/bounces + +public class GetAllBounces { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("end_time", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetAllGlobalSuppressions.java b/examples/suppression/GetAllGlobalSuppressions.java new file mode 100644 index 00000000..f714b2c9 --- /dev/null +++ b/examples/suppression/GetAllGlobalSuppressions.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all global suppressions +// GET /suppression/unsubscribes + +public class GetAllGlobalSuppressions { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/unsubscribes"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetAllInvalidEmails.java b/examples/suppression/GetAllInvalidEmails.java new file mode 100644 index 00000000..d2b2028b --- /dev/null +++ b/examples/suppression/GetAllInvalidEmails.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all invalid emails +// GET /suppression/invalid_emails + +public class GetAllInvalidEmails { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetAllSpamReports.java b/examples/suppression/GetAllSpamReports.java new file mode 100644 index 00000000..03795c45 --- /dev/null +++ b/examples/suppression/GetAllSpamReports.java @@ -0,0 +1,33 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve all spam reports +// GET /suppression/spam_reports + +public class GetAllSpamReports { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_reports"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetBounce.java b/examples/suppression/GetBounce.java new file mode 100644 index 00000000..fe3259f5 --- /dev/null +++ b/examples/suppression/GetBounce.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve a Bounce +// GET /suppression/bounces/{email} + +public class GetBounce { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetSpecificBlock.java b/examples/suppression/GetSpecificBlock.java new file mode 100644 index 00000000..1c9b8dee --- /dev/null +++ b/examples/suppression/GetSpecificBlock.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve a specific block +// GET /suppression/blocks/{email} + +public class GetSpecificBlock { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetSpecificInvalidEmail.java b/examples/suppression/GetSpecificInvalidEmail.java new file mode 100644 index 00000000..54f8f8a4 --- /dev/null +++ b/examples/suppression/GetSpecificInvalidEmail.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve a specific invalid email +// GET /suppression/invalid_emails/{email} + +public class GetSpecificInvalidEmail { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/GetSpecificSpamReport.java b/examples/suppression/GetSpecificSpamReport.java new file mode 100644 index 00000000..bd5d3826 --- /dev/null +++ b/examples/suppression/GetSpecificSpamReport.java @@ -0,0 +1,29 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve a specific spam report +// GET /suppression/spam_report/{email} + +public class GetSpecificSpamReport { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_report/{email}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/suppression/README.md b/examples/suppression/README.md new file mode 100644 index 00000000..ca686a4b --- /dev/null +++ b/examples/suppression/README.md @@ -0,0 +1,21 @@ +![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) + +This folder contains various examples on using the SUPPRESSION endpoint of SendGrid with Java: + +* [Retrieve all blocks (GET /suppression/blocks)](GetAllBlocks.java) +* [Delete blocks (DELETE /suppression/blocks)](DeleteBlocks.java) +* [Retrieve a specific block (GET /suppression/blocks/{email})](GetSpecificBlock.java) +* [Delete a specific block (DELETE /suppression/blocks/{email})](DeleteSpecificBlock.java) +* [Retrieve all bounces (GET /suppression/bounces)](GetAllBounces.java) +* [Delete bounces (DELETE /suppression/bounces)](DeleteBounces.java) +* [Retrieve a Bounce (GET /suppression/bounces/{email})](GetBounce.java) +* [Delete a bounce (DELETE /suppression/bounces/{email})](DeleteBounce.java) +* [Retrieve all invalid emails (GET /suppression/invalid_emails)](GetAllInvalidEmails.java) +* [Delete invalid emails (DELETE /suppression/invalid_emails)](DeleteInvalidEmails.java) +* [Retrieve a specific invalid email (GET /suppression/invalid_emails/{email})](GetSpecificInvalidEmail.java) +* [Delete a specific invalid email (DELETE /suppression/invalid_emails/{email})](DeleteSpecificInvalidEmail.java) +* [Retrieve a specific spam report (GET /suppression/spam_report/{email})](GetSpecificSpamReport.java) +* [Delete a specific spam report (DELETE /suppression/spam_report/{email})](DeleteSpecificSpamReport.java) +* [Retrieve all spam reports (GET /suppression/spam_reports)](GetAllSpamReports.java) +* [Delete spam reports (DELETE /suppression/spam_reports)](DeleteSpamReports.java) +* [Retrieve all global suppressions (GET /suppression/unsubscribes)](GetAllGlobalSuppressions.java) \ No newline at end of file diff --git a/examples/templates/templates.java b/examples/templates/templates.java new file mode 100644 index 00000000..4fcf3886 --- /dev/null +++ b/examples/templates/templates.java @@ -0,0 +1,234 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Create a transactional template. +// POST /templates + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates"); + request.setBody("{\"name\":\"example_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve all transactional templates. +// GET /templates + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates"); + request.addQueryParam("generations", "legacy,dynamic") + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Edit a transactional template. +// PATCH /templates/{template_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}"); + request.setBody("{\"name\":\"new_example_name\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a single transactional template. +// GET /templates/{template_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a template. +// DELETE /templates/{template_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Create a new transactional template version. +// POST /templates/{template_id}/versions + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions"); + request.setBody("{\"name\":\"example_version_name\",\"html_content\":\"<%body%>\",\"plain_content\":\"<%body%>\",\"active\":1,\"template_id\":\"ddb96bbc-9b92-425e-8979-99464621b543\",\"subject\":\"<%subject%>\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Edit a transactional template version. +// PATCH /templates/{template_id}/versions/{version_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + request.setBody("{\"active\":1,\"html_content\":\"<%body%>\",\"subject\":\"<%subject%>\",\"name\":\"updated_example_name\",\"plain_content\":\"<%body%>\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve a specific transactional template version. +// GET /templates/{template_id}/versions/{version_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Delete a transactional template version. +// DELETE /templates/{template_id}/versions/{version_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Activate a transactional template version. +// POST /templates/{template_id}/versions/{version_id}/activate + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions/{version_id}/activate"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/trackingsettings/trackingsettings.java b/examples/trackingsettings/trackingsettings.java new file mode 100644 index 00000000..17b8d0d0 --- /dev/null +++ b/examples/trackingsettings/trackingsettings.java @@ -0,0 +1,213 @@ +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sendgrid.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +////////////////////////////////////////////////////////////////// +// Retrieve Tracking Settings +// GET /tracking_settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update Click Tracking Settings +// PATCH /tracking_settings/click + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/click"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve Click Track Settings +// GET /tracking_settings/click + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/click"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update Google Analytics Settings +// PATCH /tracking_settings/google_analytics + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/google_analytics"); + request.setBody("{\"utm_campaign\":\"website\",\"utm_term\":\"\",\"utm_content\":\"\",\"enabled\":true,\"utm_source\":\"sendgrid.com\",\"utm_medium\":\"email\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve Google Analytics Settings +// GET /tracking_settings/google_analytics + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/google_analytics"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update Open Tracking Settings +// PATCH /tracking_settings/open + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/open"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Get Open Tracking Settings +// GET /tracking_settings/open + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/open"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Update Subscription Tracking Settings +// PATCH /tracking_settings/subscription + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/subscription"); + request.setBody("{\"url\":\"url\",\"html_content\":\"html content\",\"enabled\":true,\"landing\":\"landing page html\",\"replace\":\"replacement tag\",\"plain_content\":\"text content\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + +////////////////////////////////////////////////////////////////// +// Retrieve Subscription Tracking Settings +// GET /tracking_settings/subscription + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/subscription"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} + diff --git a/examples/user/CreateWebhookParseSettings.java b/examples/user/CreateWebhookParseSettings.java new file mode 100644 index 00000000..23992ea7 --- /dev/null +++ b/examples/user/CreateWebhookParseSettings.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Create a parse setting +// POST /user/webhooks/parse/settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/parse/settings"); + request.setBody("{\"url\":\"http://email.myhosthame.com\",\"send_raw\":false,\"hostname\":\"myhostname.com\",\"spam_check\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/DeleteScheduleSend.java b/examples/user/DeleteScheduleSend.java new file mode 100644 index 00000000..23b9857c --- /dev/null +++ b/examples/user/DeleteScheduleSend.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Delete a cancellation or pause of a scheduled send +// DELETE /user/scheduled_sends/{batch_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/DeleteWebhookParseSettings.java b/examples/user/DeleteWebhookParseSettings.java new file mode 100644 index 00000000..93b8763c --- /dev/null +++ b/examples/user/DeleteWebhookParseSettings.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Delete a parse setting +// DELETE /user/webhooks/parse/settings/{hostname} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetCreditBalance.java b/examples/user/GetCreditBalance.java new file mode 100644 index 00000000..c6b9db1e --- /dev/null +++ b/examples/user/GetCreditBalance.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve your credit balance +// GET /user/credits + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/credits"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetEmailAddress.java b/examples/user/GetEmailAddress.java new file mode 100644 index 00000000..7fbccf11 --- /dev/null +++ b/examples/user/GetEmailAddress.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve your account email address +// GET /user/email + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/email"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetEnforcedTLS.java b/examples/user/GetEnforcedTLS.java new file mode 100644 index 00000000..f5a21969 --- /dev/null +++ b/examples/user/GetEnforcedTLS.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve current Enforced TLS settings. +// GET /user/settings/enforced_tls + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/settings/enforced_tls"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetProfile.java b/examples/user/GetProfile.java new file mode 100644 index 00000000..5fd8b541 --- /dev/null +++ b/examples/user/GetProfile.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Get a user's profile +// GET /user/profile + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/profile"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetScheduleSend.java b/examples/user/GetScheduleSend.java new file mode 100644 index 00000000..436dd0d9 --- /dev/null +++ b/examples/user/GetScheduleSend.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve all scheduled sends +// GET /user/scheduled_sends + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetScheduleSendByBatchId.java b/examples/user/GetScheduleSendByBatchId.java new file mode 100644 index 00000000..48c4e334 --- /dev/null +++ b/examples/user/GetScheduleSendByBatchId.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve scheduled send +// GET /user/scheduled_sends/{batch_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetUserInfo.java b/examples/user/GetUserInfo.java new file mode 100644 index 00000000..880f6c5c --- /dev/null +++ b/examples/user/GetUserInfo.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Get a user's account information. +// GET /user/account + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/account"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetUsername.java b/examples/user/GetUsername.java new file mode 100644 index 00000000..e6756311 --- /dev/null +++ b/examples/user/GetUsername.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve your username +// GET /user/username + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/username"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetWebhookEventSettings.java b/examples/user/GetWebhookEventSettings.java new file mode 100644 index 00000000..fe1561c5 --- /dev/null +++ b/examples/user/GetWebhookEventSettings.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve Event Webhook settings +// GET /user/webhooks/event/settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/event/settings"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetWebhookParseSettingByHostname.java b/examples/user/GetWebhookParseSettingByHostname.java new file mode 100644 index 00000000..8814de72 --- /dev/null +++ b/examples/user/GetWebhookParseSettingByHostname.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve a specific parse setting +// GET /user/webhooks/parse/settings/{hostname} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetWebhookParseSettings.java b/examples/user/GetWebhookParseSettings.java new file mode 100644 index 00000000..deb6123c --- /dev/null +++ b/examples/user/GetWebhookParseSettings.java @@ -0,0 +1,21 @@ +////////////////////////////////////////////////////////////////// +// Retrieve all parse settings +// GET /user/webhooks/parse/settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/GetWebhookParseStatistics.java b/examples/user/GetWebhookParseStatistics.java new file mode 100644 index 00000000..52be567b --- /dev/null +++ b/examples/user/GetWebhookParseStatistics.java @@ -0,0 +1,26 @@ +////////////////////////////////////////////////////////////////// +// Retrieves Inbound Parse Webhook statistics. +// GET /user/webhooks/parse/stats + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "test_string"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/PauseScheduleSend.java b/examples/user/PauseScheduleSend.java new file mode 100644 index 00000000..517a8853 --- /dev/null +++ b/examples/user/PauseScheduleSend.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Cancel or pause a scheduled send +// POST /user/scheduled_sends + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/scheduled_sends"); + request.setBody("{\"batch_id\":\"YOUR_BATCH_ID\",\"status\":\"pause\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/README.md b/examples/user/README.md new file mode 100644 index 00000000..befb7b4f --- /dev/null +++ b/examples/user/README.md @@ -0,0 +1,50 @@ +# User examples + +## Parse Settings Examples +- [Create Webhook Parse Settings](CreateWebhookParseSettings.java) +- [Delete Webhook Parse Settings](DeleteWebhookParseSettings.java) + +## Schedule Send Examples +- [Delete Scheduled Send](DeleteScheduleSend.java) +- [Get Scheduled Send](GetScheduleSend.java) +- [Get Scheduled Send](GetScheduleSendByBatchId.java) +- [Pause Scheduled Send](PauseScheduleSend.java) +- [Update Scheduled Send](UpdateScheduleSend.java) + +## Billing Examples +- [Get Credit Balance](GetCreditBalance.java) + +## Profile Examples + +### Email Address +- [Get Email Address](GetEmailAddress.java) +- [Update Email Address](UpdateEmailAddress.java) + +### Password +- [Update Password](UpdatePassword.java) + +### Profile +- [Get Profile](GetProfile.java) +- [Get User Info](GetUserInfo.java) +- [Update Profile](UpdateProfile.java) + +### Username +- [Get Username](GetUsername.java) +- [Update Username](UpdateUsername.java) + +## Security Settings Examples +- [Get Enforced TLS](GetEnforcedTLS.java) +- [Update Enforced TLS](UpdateEnforcedTLS.java) + +## Webhook Settings Examples + +### Event Webhook +- [Test Event Webhook](TestWebhookEvent.java) +- [Get Event Webhook Settings](GetWebhookEventSettings.java) +- [Get Event Webhook Settings by Hostname](GetWebhookParseSettingByHostname.java) +- [Update Event Webhook Settings](UpdateWebhookEventSettings.java) + +## Inbound Parse +- [Get Parse Webhook Settings](GetWebhookParseSettings.java) +- [Get Parse Webhook Settings](GetWebhookParseStatistics.java) +- [Update Parse Webhook Settings](UpdateWebhookParseSettings.java) diff --git a/examples/user/TestWebhookEvent.java b/examples/user/TestWebhookEvent.java new file mode 100644 index 00000000..3dddac20 --- /dev/null +++ b/examples/user/TestWebhookEvent.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Test Event Notification Settings +// POST /user/webhooks/event/test + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/event/test"); + request.setBody("{\"url\":\"url\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateEmailAddress.java b/examples/user/UpdateEmailAddress.java new file mode 100644 index 00000000..dc0fd90e --- /dev/null +++ b/examples/user/UpdateEmailAddress.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update your account email address +// PUT /user/email + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/email"); + request.setBody("{\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateEnforcedTLS.java b/examples/user/UpdateEnforcedTLS.java new file mode 100644 index 00000000..0de1b829 --- /dev/null +++ b/examples/user/UpdateEnforcedTLS.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update Enforced TLS settings +// PATCH /user/settings/enforced_tls + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/settings/enforced_tls"); + request.setBody("{\"require_tls\":true,\"require_valid_cert\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/user/UpdatePassword.java b/examples/user/UpdatePassword.java new file mode 100644 index 00000000..b61e2228 --- /dev/null +++ b/examples/user/UpdatePassword.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update your password +// PUT /user/password + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/password"); + request.setBody("{\"new_password\":\"new_password\",\"old_password\":\"old_password\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} diff --git a/examples/user/UpdateProfile.java b/examples/user/UpdateProfile.java new file mode 100644 index 00000000..d86d6523 --- /dev/null +++ b/examples/user/UpdateProfile.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update a user's profile +// PATCH /user/profile + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/profile"); + request.setBody("{\"city\":\"Orange\",\"first_name\":\"Example\",\"last_name\":\"User\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateScheduleSend.java b/examples/user/UpdateScheduleSend.java new file mode 100644 index 00000000..5f8c5d09 --- /dev/null +++ b/examples/user/UpdateScheduleSend.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update user scheduled send information +// PATCH /user/scheduled_sends/{batch_id} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + request.setBody("{\"status\":\"pause\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateUsername.java b/examples/user/UpdateUsername.java new file mode 100644 index 00000000..470dfb1a --- /dev/null +++ b/examples/user/UpdateUsername.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update your username +// PUT /user/username + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setBody("user/username"); + request.setBody("{\"username\":\"test_username\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateWebhookEventSettings.java b/examples/user/UpdateWebhookEventSettings.java new file mode 100644 index 00000000..13b61488 --- /dev/null +++ b/examples/user/UpdateWebhookEventSettings.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update Event Notification Settings +// PATCH /user/webhooks/event/settings + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/event/settings"); + request.setBody("{\"group_resubscribe\":true,\"delivered\":true,\"group_unsubscribe\":true,\"spam_report\":true,\"url\":\"url\",\"enabled\":true,\"bounce\":true,\"deferred\":true,\"unsubscribe\":true,\"dropped\":true,\"open\":true,\"click\":true,\"processed\":true}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/examples/user/UpdateWebhookParseSettings.java b/examples/user/UpdateWebhookParseSettings.java new file mode 100644 index 00000000..bbb0b8f4 --- /dev/null +++ b/examples/user/UpdateWebhookParseSettings.java @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////// +// Update a parse setting +// PATCH /user/webhooks/parse/settings/{hostname} + + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + request.setBody("{\"url\":\"http://newdomain.com/parse\",\"send_raw\":true,\"spam_check\":false}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} \ No newline at end of file diff --git a/gradle.properties.example b/gradle.properties.example deleted file mode 100644 index cde593ea..00000000 --- a/gradle.properties.example +++ /dev/null @@ -1,6 +0,0 @@ -signing.keyId= -signing.password= -signing.secretKeyRingFile=/Users/yourusername/.gnupg/secring.gpg - -sonatypeUsername= -sonatypePassword= diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 0087cd3b..00000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index b0c3cf1e..00000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Mon May 26 17:38:02 PDT 2014 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-1.8-bin.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index 91a7e269..00000000 --- a/gradlew +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index aec99730..00000000 --- a/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/maven-help.png b/maven-help.png deleted file mode 100644 index fe475a04..00000000 Binary files a/maven-help.png and /dev/null differ diff --git a/pom.xml b/pom.xml index f8647eba..0d8ec8ef 100644 --- a/pom.xml +++ b/pom.xml @@ -1,122 +1,304 @@ - + - 4.0.0 - - org.sonatype.oss - oss-parent - 7 - - com.sendgrid - sendgrid-java - SendGrid Java helper library - 2.1.1 - This Java module allows you to quickly and easily send emails through SendGrid using Java. + 4.0.0 + com.sendgrid + sendgrid-java + Twilio SendGrid Java helper library + 4.10.3 + This Java module allows you to quickly and easily send emails through Twilio SendGrid using Java. + https://github.com/sendgrid/sendgrid-java + + + The MIT License (MIT) + https://github.com/sendgrid/java-http-client/blob/HEAD/LICENSE + repo + + + + 2.14.0 + + https://github.com/sendgrid/sendgrid-java - - - Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0.html - repo - - - - https://github.com/sendgrid/sendgrid-java - scm:git:git@github.com:sendgrid/sendgrid-java.git - scm:git:git@github.com:sendgrid/sendgrid-java.git - HEAD + scm:git:git@github.com:sendgrid/sendgrid-java.git + scm:git:git@github.com:sendgrid/sendgrid-java.git + 4.10.3 - + + + release + + + release + + + - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 + + org.sonatype.central + central-publishing-maven-plugin + 0.8.0 + true + + central + true + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + - 1.5 - 1.5 + ${gpg.keyname} + ${gpg.passphrase} + + --pinentry-mode + loopback + - - - org.apache.maven.plugins - maven-release-plugin - 2.4.2 - - - org.apache.maven.scm - maven-scm-provider-gitexe - 1.8.1 - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + + com.sendgrid.helpers.mail.objects + com.sendgrid + + + com.sendgrid.helpers.mail + com.sendgrid + + + + + + package + + shade + + + true + shaded + + + + - - - - johnclaus - John Claus - johnclaus@fastmail.fm - http://johnclaus.com - -7 - - - jar - - - com.sendgrid - smtpapi-java - 1.1.1 - - - org.apache.httpcomponents - httpcore - 4.3.2 - - - org.apache.httpcomponents - httpclient - 4.3.4 - - - org.apache.httpcomponents - httpmime - 4.3.4 - - - org.json - json - 20140107 - - - junit - junit-dep - 4.10 - test - - - + + + + + + + ${basedir} + + LICENSE + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-release-plugin + 2.4.2 + + + org.apache.maven.scm + maven-scm-provider-gitexe + 1.8.1 + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.1 + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + + com.sendgrid.helpers.mail.objects + com.sendgrid + + + com.sendgrid.helpers.mail + com.sendgrid + + + + + + package + + shade + + + true + shaded + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.0.4 + + + com.github.spotbugs + spotbugs + 4.0.4 + + + + + + + + thinkingserious + Elmer Thomas + ethomas@twilio.com + https://sendgrid.com + + + jar + + + com.sendgrid + java-http-client + 4.5.0 + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + junit + junit-dep + 4.11 + test + + + org.mockito + mockito-core + 2.28.2 + test + + + org.bouncycastle + bcprov-jdk18on + 1.78.1 + test + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.0.0 + + + + \ No newline at end of file diff --git a/proposals/mail-helper-refactor.md b/proposals/mail-helper-refactor.md new file mode 100644 index 00000000..bd6d000b --- /dev/null +++ b/proposals/mail-helper-refactor.md @@ -0,0 +1,465 @@ +# Send a Single Email to a Single Recipient + +The following code assumes you are storing the API key in an environment variable (recommended). + +This is the minimum code needed to send an email. + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + To to = new To("test@example.com", "Example User"); + Subject subject = new Subject("Sending with Twilio SendGrid is Fun"); + PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java"); + HtmlContent htmlContent = new HtmlContent("and easy to do anywhere, even with Java"); + SendGridMessage email = new SendGridMessage(from, + to, + subject, + plainTextContent, + htmlContent); + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` + +# Send a Single Email to Multiple Recipients + +The following code assumes you are storing the API key in an environment variable (recommended). + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; +import java.util.ArrayList; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + ArrayList tos = new ArrayList(); + tos.add(new To("test1@example.com", "Example User1")); + tos.add(new To("test2@example.com", "Example User2")); + tos.add(new To("test3@example.com", "Example User3")); + Subject subject = new Subject("Sending with Twilio SendGrid is Fun"); + PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java"); + HtmlContent htmlContent = new HtmlContent("and easy to do anywhere, even with Java"); + SendGridMessage email = new SendGridMessage(from, + tos, + subject, + plainTextContent, + htmlContent); + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` + +# Send Multiple Emails to Multiple Recipients + +The following code assumes you are storing the API key in an environment variable (recommended). + + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; +import java.util.ArrayList; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + ArrayList tos = new ArrayList(); + ArrayList sub = new ArrayList(); + sub.add("-name-", "Alain"); + sub.add("-github-", "http://github.com/ninsuo"); + tos.add(new To("test1@example.com", "Example User1"), sub); + sub.clear(); + sub.add("-name-", "Elmer"); + sub.add("-github-", "http://github.com/thinkingserious"); + tos.add(new To("test2@example.com", "Example User2"), sub); + sub.clear(); + sub.add("-name-", "Casey"); + sub.add("-github-", "http://github.com/caseyw"); + tos.add(new To("test3@example.com", "Example User3"), sub); + // Alternatively, you can pass in a collection of subjects OR add a subject to the `To` object + Subject subject = new Subject("Hi -name-!"); + Substitution globalSubstitution = new Substitution("-time-", ""); + PlainTextContent plainTextContent = new PlainTextContent("Hello -name-, your github is -github-, email sent at -time-"); + HtmlContent htmlContent = new HtmlContent("Hello -name-, your github is here email sent at -time-"); + SendGridMessage email = new SendGridMessage(from, + subject, // or subjects, + tos, + plainTextContent, + htmlContent, + globalSubstitution); // or globalSubstitutions + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` + +# Kitchen Sink - an example with all settings used + +The following code assumes you are storing the API key in an environment variable (recommended). + + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; +import java.util.ArrayList; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + To to = new To("test@example.com", "Example User"); + Subject subject = new Subject("Sending with Twilio SendGrid is Fun"); + PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java"); + HtmlContent htmlContent = new HtmlContent("and easy to do anywhere, even with Java"); + SendGridMessage email = new SendGridMessage(from, + to, // or tos + subject, // or subjects + plainTextContent, + htmlContent); + + // For a detailed description of each of these settings, please see the [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html). + email.addTo("test1@example.com", "Example User1") + ArrayList tos = new ArrayList(); + tos.add("test2@example.com", "Example User2"); + tos.add("test3@example.com", "Example User3"); + email.addTos(tos); + + email.addCc("test4@example.com", "Example User4") + ArrayList ccs = new ArrayList(); + ccs.add("test5@example.com", "Example User5"); + ccs.add("test6@example.com", "Example User6"); + email.addCcs(ccs); + + email.addBcc("test7@example.com", "Example User7") + ArrayList bccs = new ArrayList(); + bccs.add("test8@example.com", "Example User8"); + bccs.add("test9@example.com", "Example User9"); + email.addBccs(bccs); + + email.addHeader("X-Test1", "Test1"); + email.addHeader("X-Test2", "Test2"); + ArrayList
headers = new ArrayList
(); + headers.add("X-Test3", "Test3"); + headers.add("X-Test4", "Test4"); + email.addHeaders(headers) + + email.addSubstitution("%name1%", "Example Name 1"); + email.addSubstitution("%city1%", "Denver"); + ArrayList substitutions = new ArrayList(); + substitutions.add("%name2%", "Example Name 2"); + substitutions.add("%city2%", "Orange" ); + email.addSubstitutions(substitutions); + + email.addCustomArg("marketing1", "false"); + email.addCustomArg("transactional1", "true"); + ArrayList customArgs = new ArrayList(); + customArgs.add("marketing2", "true"); + customArgs.add("transactional2", "false"); + email.addCustomArgs(customArgs); + + email.setSendAt(1461775051); + + // If you need to add more [Personalizations](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html), here is an example of adding another Personalization by passing in a personalization index + + + email.addTo("test10@example.com", "Example User 10", 1); + ArrayList tos1 = new ArrayList(); + tos1.add("test11@example.com", "Example User11"); + tos1.add("test12@example.com", "Example User12"); + email.addTos(tos1, 1); + + email.addCc("test13@example.com", "Example User 13", 1); + ArrayList ccs1 = new ArrayList(); + ccs1.add("test14@example.com", "Example User14"); + ccs1.add("test15@example.com", "Example User15"); + email.addCcs(ccs1, 1); + + email.addBcc("test16@example.com", "Example User 16", 1); + ArrayList bccs1 = new ArrayList(); + bccs1.add("test17@example.com", "Example User17"); + bccs1.add("test18@example.com", "Example User18"); + email.addBccs(bccs1, 1); + + email.addHeader("X-Test5", "Test5", 1); + email.addHeader("X-Test6", "Test6", 1); + ArrayList
headers1 = new ArrayList
(); + headers1.add("X-Test7", "Test7"); + headers1.add("X-Test8", "Test8"); + email.addHeaders(headers1, 1); + + email.addSubstitution("%name3%", "Example Name 3", 1); + email.addSubstitution("%city3%", "Redwood City", 1); + ArrayList substitutions1 = new ArrayList(); + substitutions1.add("%name4%", "Example Name 4"); + substitutions1.add("%city4%", "London"); + var substitutions1 = new Dictionary() + email.addSubstitutions(substitutions1, 1); + + email.addCustomArg("marketing3", "true", 1); + email.addCustomArg("transactional3", "false", 1); + ArrayList customArgs1 = new ArrayList(); + customArgs1.add("marketing4", "false"); + customArgs1.add("transactional4", "true"); + email.addCustomArgs(customArgs1, 1); + + email.setSendAt(1461775052, 1); + + // The values below this comment are global to entire message + + email.setFrom("test@example.com", "Example User 0"); + + email.setSubject("this subject overrides the Global Subject"); + + email.setGlobalSubject("Sending with Twilio SendGrid is Fun"); + + email.addContent(MimeType.TEXT, "and easy to do anywhere, even with C#"); + email.addContent(MimeType.HTML, "and easy to do anywhere, even with C#"); + ArrayList contents = new ArrayList(); + contents.add("text/calendar", "Party Time!!"); + contents.add("text/calendar2", "Party Time2!!"); + email.addContents(contents); + + email.addAttachment("balance_001.pdf", + "base64 encoded string", + "application/pdf", + "attachment", + "Balance Sheet"); + ArrayList attachments = new ArrayList(); + attachments.add("banner.png", + "base64 encoded string", + "image/png", + "inline", + "Banner"); + attachments.add("banner2.png", + "base64 encoded string", + "image/png", + "inline", + "Banner2"); + email.addAttachments(attachments); + + email.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + + email.addGlobalHeader("X-Day", "Monday"); + ArrayList
globalHeaders = new ArrayList
(); + globalHeaders.add("X-Month", "January" ); + globalHeaders.add("X-Year", "2017"); + email.addGlobalHeaders(globalHeaders); + + email.addSection("%section1", "Substitution for Section 1 Tag"); + ArrayList
sections = new ArrayList
(); + sections.add("%section2%", "Substitution for Section 2 Tag"); + sections.add("%section3%", "Substitution for Section 3 Tag"); + email.addSections(sections); + + email.addCategory("customer"); + ArrayList categories = new ArrayList(); + categories.add("vip"); + categories.add("new_account"); + email.addCategories(categories); + + email.addGlobalCustomArg("campaign", "welcome"); + ArrayList globalCustomArgs = new ArrayList(); + globalCustomArgs.add("sequence2", "2"); + globalCustomArgs.add("sequence3", "3"); + email.addGlobalCustomArgs(globalCustomArgs); + + ArrayList asmGroups = new ArrayList(); + asmGroups.add(1); + asmGroups.add(4); + asmGroups.add(5); + email.setAsm(3, asmGroups); + + email.setGlobalSendAt(1461775051); + + email.setIpPoolName("23"); + + // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) + //email.setBatchId("some_batch_id"); + + email.setBccSetting(true, "test@example.com"); + + email.setBypassListManagement(true); + + email.setFooterSetting(true, "Some Footer HTML", "Some Footer Text"); + + email.setSandBoxMode(true); + + email.setSpamCheck(true, 1, "https://gotchya.example.com"); + + email.setClickTracking(true, false); + + email.setOpenTracking(true, "Optional tag to replace with the open image in the body of the message"); + + email.setSubscriptionTracking(true, + "HTML to insert into the text / html portion of the message", + "text to insert into the text/plain portion of the message", + "substitution tag"); + + email.setGoogleAnalytics(true, + "some campaign", + "some content", + "some medium", + "some source", + "some term"); + + email.setReplyTo("test+reply@example.com", "Reply To Me"); + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` + +# Attachments + +The following code assumes you are storing the API key in an environment variable (recommended). + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + To to = new To("test@example.com", "Example User"); + Subject subject = new Subject("Sending with Twilio SendGrid is Fun"); + PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java"); + HtmlContent htmlContent = new HtmlContent("and easy to do anywhere, even with Java"); + SendGridMessage email = new SendGridMessage(from, + to, + subject, + plainTextContent, + htmlContent); + email.addAttachment("balance_001.pdf", + "base64 encoded string", + "application/pdf", + "attachment", + "Balance Sheet"); + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` + +# Transactional Templates + +The following code assumes you are storing the API key in an environment variable (recommended). + +For this example, we assume you have created a [transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html). Following is the template content we used for testing. + +Template ID (replace with your own): + +```text +13b8f94f-bcae-4ec6-b752-70d6cb59f932 +``` + +Email Subject: + +```text +<%subject%> +``` + +Template Body: + +```html + + + + + +Hello -name-, +

+I'm glad you are trying out the template feature! +

+<%body%> +

+I hope you are having a great day in -city- :) +

+ + +``` + + +```java +import com.sendgrid.*; +import com.sendgrid.helpers.mail.*; + +public class SendGridExample { + public static void main(String[] args) throws SendGridException { + From from = new From("test@example.com", "Example User"); + To to = new To("test@example.com", "Example User"); + Subject subject = new Subject("Sending with Twilio SendGrid is Fun"); + PlainTextContent plainTextContent = new PlainTextContent("and easy to do anywhere, even with Java"); + HtmlContent htmlContent = new HtmlContent("and easy to do anywhere, even with Java"); + SendGridMessage email = new SendGridMessage(from, + to, + subject, + plainTextContent, + htmlContent); + // See `Send Multiple Emails to Multiple Recipients` for additional methods for adding substitutions + email.addSubstitution("-name-", "Example User"); + email.addSubstitution("-city-", "Denver"); + email.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + + SendGrid sendgrid = new SendGrid(System.getenv("SENDGRID_API_KEY")); + try { + SendGridResponse response = sendgrid.send(email); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (SendGridException ex) { + System.err.println(ex); + throw ex; + } + } +} +``` diff --git a/publishing.md b/publishing.md deleted file mode 100644 index 04f66283..00000000 --- a/publishing.md +++ /dev/null @@ -1,52 +0,0 @@ -## Publishing to Maven - -This only works if you have the correct permissions - for admins only basically. - -Let's begin with the permissions. - -``` -cp gradle.properties.example ~/.gradle/gradle.properties -``` - -Edit that file and set your `sonatypeUsername` and sonatypePassword`. You also need to set the values for your keys. Here's how to list/create them. [1](http://central.sonatype.org/pages/working-with-pgp-signatures.html). - -``` -gpg --list-keys -gpg --gen-key -``` - -Set the signing.KeyId, signing.password, and the signing.secretKeyRingFile. - -The signing.KeyId is the 'pub' one. It's the part of your list of keys that looks something like this: `2048R/5D64A177`. So in this scenario it would be `5D64A177`. [1](http://www.gradle.org/docs/current/userguide/signing_plugin.html) [2](http://yennicktrevels.com/blog/2013/10/11/automated-gradle-project-deployment-to-sonatype-oss-repository/) - -The signing.password is the password you used when generating this key. It could be blank if you didn't use a password. - -The signing.secretKeyRingFile is the path to the secring.gpg. - -Now, upload that key to the keyserver. - -``` -gpg --keyserver hkp://pool.sks-keyservers.net --send-keys 5D64A177 -``` - -Now, you can finally upload! Ah, Java! - -``` -./gradlew uploadArchives -``` - -Login to [Sonatype](https://oss.sonatype.org/index.html#stagingRepositories). - -Go to [staging repositories page](https://oss.sonatype.org/index.html#stagingRepositories). - -Click 'Close' with the archive selected. - -![](https://raw.githubusercontent.com/sendgrid/sendgrid-java/master/maven-help.png) - -Wait a few minutes, and refresh the staging repositories page. - -Check the box for the SendGrid repo again and this time click 'Release'. - -You're all done. - -[Further help](https://github.com/sendgrid/sendgrid-java/pull/15). diff --git a/scripts/generate_upload_policy.php b/scripts/generate_upload_policy.php deleted file mode 100755 index 18fdf829..00000000 --- a/scripts/generate_upload_policy.php +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env php -$blocksize) - $key=pack('H*', $hashfunc($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack( - 'H*',$hashfunc( - ($key^$opad).pack( - 'H*',$hashfunc( - ($key^$ipad).$data - ) - ) - ) - ); - return bin2hex($hmac); -} - -/* - * Used to encode a field for Amazon Auth - * (taken from the Amazon S3 PHP example library) - */ -function hex2b64($str) -{ - $raw = ''; - for ($i=0; $i < strlen($str); $i+=2) - { - $raw .= chr(hexdec(substr($str, $i, 2))); - } - return base64_encode($raw); -} - -if (count($argv) != 3) { - echo "Usage: " . $argv[0] . " \n"; - exit(1); -} - -$policy = file_get_contents($argv[1]); -$secret = $argv[2]; - -/* - * Base64 encode the Policy Document and then - * create HMAC SHA-1 signature of the base64 encoded policy - * using the secret key. Finally, encode it for Amazon Authentication. - */ -$base64_policy = base64_encode($policy); -$signature = hex2b64(hmacsha1($secret, $base64_policy)); -echo "S3_POLICY=\"" . $base64_policy . "\"\nS3_SIGNATURE=\"" . $signature . "\"\n" -?> diff --git a/scripts/s3policy.json b/scripts/s3policy.json deleted file mode 100755 index 01c8108e..00000000 --- a/scripts/s3policy.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "expiration": "2100-01-01T12:00:00.000Z", - "conditions": [ - {"acl": "public-read" }, - {"bucket": "sendgrid-open-source" }, - ["starts-with", "$key", "sendgrid-java/"], - ["content-length-range", 2048, 268435456], - ["eq", "$Content-Type", "application/zip"] - ] -} diff --git a/scripts/s3upload.sh b/scripts/s3upload.sh deleted file mode 100755 index 420580a5..00000000 --- a/scripts/s3upload.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -# From: -# http://raamdev.com/2008/using-curl-to-upload-files-via-post-to-amazon-s3/ - -GIT_VERSION=`git rev-parse --short HEAD` - -curl -X POST \ - -F "key=sendgrid-java/versions/sendgrid-java-$GIT_VERSION.jar" \ - -F "acl=public-read" \ - -F "AWSAccessKeyId=$S3_ACCESS_KEY" \ - -F "Policy=$S3_POLICY" \ - -F "Signature=$S3_SIGNATURE" \ - -F "Content-Type=application/zip" \ - -F "file=@./repo/com/sendgrid/sendgrid-jar.jar" \ - https://s3.amazonaws.com/$S3_BUCKET - -if [ "$TRAVIS_BRANCH" = "master" ] -then - curl -X POST \ - -F "key=sendgrid-java/sendgrid-java.jar" \ - -F "acl=public-read" \ - -F "AWSAccessKeyId=$S3_ACCESS_KEY" \ - -F "Policy=$S3_POLICY" \ - -F "Signature=$S3_SIGNATURE" \ - -F "Content-Type=application/zip" \ - -F "file=@./repo/com/sendgrid/sendgrid-jar.jar" \ - https://s3.amazonaws.com/$S3_BUCKET -fi - -exit 0 diff --git a/src/main/java/com/sendgrid/APICallback.java b/src/main/java/com/sendgrid/APICallback.java new file mode 100644 index 00000000..101052d6 --- /dev/null +++ b/src/main/java/com/sendgrid/APICallback.java @@ -0,0 +1,22 @@ +package com.sendgrid; + +/** + * An interface describing a callback mechanism for the asynchronous, rate limit aware API + * connection. + */ +public interface APICallback { + + /** + * Callback method in case of an error. + * + * @param ex the error that was thrown. + */ + void error(Exception ex); + + /** + * Callback method in case of a valid response. + * + * @param response the valid response. + */ + void response(Response response); +} diff --git a/src/main/java/com/sendgrid/BaseInterface.java b/src/main/java/com/sendgrid/BaseInterface.java new file mode 100644 index 00000000..7a45cda4 --- /dev/null +++ b/src/main/java/com/sendgrid/BaseInterface.java @@ -0,0 +1,364 @@ +package com.sendgrid; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * This class is the base interface to the Twilio SendGrid Web API. + */ +public abstract class BaseInterface implements SendGridAPI { + + private static final String VERSION = "4.10.3"; + + private static final String USER_AGENT = "sendgrid/" + VERSION + ";java"; + private static final int RATE_LIMIT_RESPONSE_CODE = 429; + private static final int THREAD_POOL_SIZE = 8; + + private static final Map allowedRegionsHostMap; + static { + //todo: change this to Map.of() when we've moved on from Java 8 + allowedRegionsHostMap = new HashMap<>(); + allowedRegionsHostMap.put("eu", "api.eu.sendgrid.com"); + allowedRegionsHostMap.put("global", "api.sendgrid.com"); + } + private ExecutorService pool; + + /** + * The host to which to connect. + */ + private String host; + + /** + * The API version. + */ + private String version; + + /** + * The HTTP client. + */ + private Client client; + + /** + * The request headers container. + */ + private Map requestHeaders; + + /** + * The number of times to try after a rate limit. + */ + private int rateLimitRetry; + + /** + * The number of milliseconds to sleep between retries. + */ + private int rateLimitSleep; + + /** + * The subuser to be impersonated. + */ + private String subuser; + + /** + * Construct a new API wrapper. + */ + public BaseInterface() { + this.client = new Client(); + } + + /** + * Construct a new API wrapper. + * + * @param test is true if you are unit testing + */ + public BaseInterface(final Boolean test) { + this.client = new Client(test); + } + + /** + * Construct a new API wrapper. + * + * @param client the Client to use (allows to customize its configuration) + */ + public BaseInterface(final Client client) { + this.client = client; + } + + /** + * Initialize the client. + * + * @param auth authorization header value + * @param host the base URL for the API + */ + public void initialize(final String auth, final String host) { + this.host = host; + this.version = "v3"; + this.requestHeaders = new HashMap<>(); + this.requestHeaders.put("Authorization", auth); + this.requestHeaders.put("User-Agent", USER_AGENT); + this.requestHeaders.put("Accept", "application/json"); + this.rateLimitRetry = 5; + this.rateLimitSleep = 1100; + + this.pool = Executors.newFixedThreadPool(THREAD_POOL_SIZE); + } + + /** + * Get the current library version. + * + * @return the current version + */ + public String getLibraryVersion() { + return VERSION; + } + + /** + * Get the API version. + * + * @return the current API version + */ + public String getVersion() { + return this.version; + } + + /** + * Set the API version. + * + * @param version the new version + */ + public void setVersion(final String version) { + this.version = version; + } + + /** + * Get the request headers. + * + * @return the request headers + */ + public Map getRequestHeaders() { + return this.requestHeaders; + } + + /** + * Add/update a request header. + * + * @param key the header key + * @param value the header value + * @return the new set of request headers + */ + public Map addRequestHeader(final String key, final String value) { + this.requestHeaders.put(key, value); + return getRequestHeaders(); + } + + /** + * Remove a request header. + * + * @param key the header key to remove + * @return the new set of request headers + */ + public Map removeRequestHeader(final String key) { + this.requestHeaders.remove(key); + return getRequestHeaders(); + } + + /** + * Get the host. + * + * @return the host + */ + public String getHost() { + return this.host; + } + + /** + * Set the host. + * + * @param host the new host + */ + public void setHost(final String host) { + this.host = host; + } + + /** + * Get the maximum number of retries on a rate limit response. + * The default is 5. + * + * @return the number of retries on a rate limit + */ + public int getRateLimitRetry() { + return this.rateLimitRetry; + } + + /** + * Set the maximum number of retries on a rate limit response. + * + * @param rateLimitRetry the maximum retry count + */ + public void setRateLimitRetry(final int rateLimitRetry) { + this.rateLimitRetry = rateLimitRetry; + } + + /** + * Get the duration of time (in milliseconds) to sleep between + * consecutive rate limit retries. The Twilio SendGrid API enforces + * the rate limit to the second. The default value is 1.1 seconds. + * + * @return the sleep duration + */ + public int getRateLimitSleep() { + return this.rateLimitSleep; + } + + /** + * Set the duration of time (in milliseconds) to sleep between + * consecutive rate limit retries. + * + * @param rateLimitSleep the sleep duration + */ + public void setRateLimitSleep(final int rateLimitSleep) { + this.rateLimitSleep = rateLimitSleep; + } + + /** + * Impersonate subuser for subsequent requests + * + * @param subuser the subuser to be impersonated + */ + public void addImpersonateSubuser(final String subuser) { + this.subuser = subuser; + this.addRequestHeader("on-behalf-of", subuser); + } + + /** + * Stop Impersonating the subuser + */ + public void removeImpersonateSubuser() { + this.subuser = null; + this.removeRequestHeader("on-behalf-of"); + } + + /** + * Get the impersonated subuser or null if empty + * + * @return the impersonated subuser + */ + public String getImpersonateSubuser() { + return this.subuser; + } + + /** + * Makes the call to the Twilio SendGrid API, override this method for testing. + * + * @param request the request to make + * @return the response object + * @throws IOException in case of a network error + */ + public Response makeCall(final Request request) throws IOException { + return client.api(request); + } + + /** + * Class api sets up the request to the Twilio SendGrid API, this is main interface. + * + * @param request the request object + * @return the response object + * @throws IOException in case of a network error + */ + public Response api(final Request request) throws IOException { + final Request req = new Request(); + + req.setMethod(request.getMethod()); + req.setBaseUri(this.host); + req.setEndpoint("/" + version + "/" + request.getEndpoint()); + req.setBody(request.getBody()); + + req.getHeaders().putAll(this.requestHeaders); + req.getHeaders().putAll(request.getHeaders()); + req.getQueryParams().putAll(request.getQueryParams()); + + return makeCall(req); + } + + /** + * Attempt an API call. This method executes the API call asynchronously + * on an internal thread pool. If the call is rate limited, the thread + * will retry up to the maximum configured time. + * + * @param request the API request + */ + public void attempt(final Request request) { + this.attempt(request, new APICallback() { + @Override + public void error(final Exception ex) { + } + + public void response(final Response r) { + } + }); + } + + /** + * Attempt an API call. This method executes the API call asynchronously + * on an internal thread pool. If the call is rate limited, the thread + * will retry up to the maximum configured time. The supplied callback + * will be called in the event of an error, or a successful response. + * + * @param request the API request + * @param callback the callback + */ + public void attempt(final Request request, final APICallback callback) { + this.pool.execute(new Runnable() { + @Override + public void run() { + Response response; + + // Retry until the retry limit has been reached. + for (int i = 0; i < rateLimitRetry; ++i) { + try { + response = api(request); + } catch (IOException ex) { + // Stop retrying if there is a network error. + callback.error(ex); + return; + } + + // We have been rate limited. + if (response.getStatusCode() == RATE_LIMIT_RESPONSE_CODE) { + try { + Thread.sleep(rateLimitSleep); + } catch (InterruptedException ex) { + // Can safely ignore this exception and retry. + } + } else { + callback.response(response); + return; + } + } + + // Retries exhausted. Return error. + callback.error(new RateLimitException(request, rateLimitRetry)); + } + }); + } + + /* + * Client libraries contain setters for specifying region/edge. + * This allows support global and eu regions only. This set will likely expand in the future. + * Global should be the default + * Global region means the message should be sent through: + * HTTP: api.sendgrid.com + * EU region means the message should be sent through: + * HTTP: api.eu.sendgrid.com +*/ + public void setDataResidency(String region){ + if (allowedRegionsHostMap.containsKey(region)){ + this.host = allowedRegionsHostMap.get(region); + } + else{ + throw new IllegalArgumentException("region can only be \"eu\" or \"global\""); + } + } +} diff --git a/src/main/java/com/sendgrid/RateLimitException.java b/src/main/java/com/sendgrid/RateLimitException.java new file mode 100644 index 00000000..5f25a075 --- /dev/null +++ b/src/main/java/com/sendgrid/RateLimitException.java @@ -0,0 +1,40 @@ +package com.sendgrid; + +/** + * An exception thrown when the maximum number of retries have occurred, and the API calls are still + * rate limited. + */ +public class RateLimitException extends Exception { + + private final Request request; + private final int retryCount; + + /** + * Construct a new exception. + * + * @param request the originating request object. + * @param retryCount the number of times a retry was attempted. + */ + public RateLimitException(Request request, int retryCount) { + this.request = request; + this.retryCount = retryCount; + } + + /** + * Get the originating request object. + * + * @return the request object. + */ + public Request getRequest() { + return this.request; + } + + /** + * Get the number of times the action was attempted. + * + * @return the retry count. + */ + public int getRetryCount() { + return this.retryCount; + } +} diff --git a/src/main/java/com/sendgrid/SendGrid.java b/src/main/java/com/sendgrid/SendGrid.java index 1c9efaab..e30a00f2 100644 --- a/src/main/java/com/sendgrid/SendGrid.java +++ b/src/main/java/com/sendgrid/SendGrid.java @@ -1,492 +1,47 @@ package com.sendgrid; -import com.sendgrid.smtpapi.SMTPAPI; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.json.JSONObject; - -import java.io.*; -import java.util.*; - -public class SendGrid { - private static final String VERSION = "2.2.2"; - private static final String USER_AGENT = "sendgrid/" + VERSION + ";java"; - - private static final String PARAM_TO = "to[]"; - private static final String PARAM_TONAME = "toname[]"; - private static final String PARAM_CC = "cc[]"; - private static final String PARAM_BCC = "bcc[]"; - - private static final String PARAM_FROM = "from"; - private static final String PARAM_FROMNAME = "fromname"; - private static final String PARAM_REPLYTO = "replyto"; - private static final String PARAM_SUBJECT = "subject"; - private static final String PARAM_HTML = "html"; - private static final String PARAM_TEXT = "text"; - private static final String PARAM_FILES = "files[%s]"; - private static final String PARAM_CONTENTS = "content[%s]"; - private static final String PARAM_XSMTPAPI = "x-smtpapi"; - private static final String PARAM_HEADERS = "headers"; - private static final String TEXT_PLAIN = "text/plain"; - private static final String UTF_8 = "UTF-8"; - - - private String username; - private String password; - private String url; - private String port; - private String endpoint; - private CloseableHttpClient client; - - /** - * Constructor for using a username and password - * - * @param username SendGrid username - * @param password SendGrid password - */ - public SendGrid(String username, String password) { - this.username = username; - this.password = password; - this.url = "https://api.sendgrid.com"; - this.endpoint = "/api/mail.send.json"; - this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); - } - - /** - * Constructor for using an API key - * - * @param apiKey SendGrid api key - */ - public SendGrid(String apiKey) { - this.password = apiKey; - this.username = null; - this.url = "https://api.sendgrid.com"; - this.endpoint = "/api/mail.send.json"; - this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); - } - - public SendGrid setUrl(String url) { - this.url = url; - return this; - } - - public SendGrid setEndpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - public String getVersion() { - return VERSION; - } - - public SendGrid setClient(CloseableHttpClient client) { - this.client = client; - return this; - } - - public HttpEntity buildBody(Email email) { - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - - // We are using an API key - if (this.username != null) { - builder.addTextBody("api_user", this.username); - builder.addTextBody("api_key", this.password); - } - - String[] tos = email.getTos(); - String[] tonames = email.getToNames(); - String[] ccs = email.getCcs(); - String[] bccs = email.getBccs(); - - // If SMTPAPI Header is used, To is still required. #workaround. - if (tos.length == 0) { - builder.addTextBody(String.format(PARAM_TO, 0), email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8)); - } - for (int i = 0, len = tos.length; i < len; i++) - builder.addTextBody(PARAM_TO, tos[i], ContentType.create("text/plain", "UTF-8")); - for (int i = 0, len = tonames.length; i < len; i++) - builder.addTextBody(PARAM_TONAME, tonames[i], ContentType.create("text/plain", "UTF-8")); - for (int i = 0, len = ccs.length; i < len; i++) - builder.addTextBody(PARAM_CC, ccs[i], ContentType.create("text/plain", "UTF-8")); - for (int i = 0, len = bccs.length; i < len; i++) - builder.addTextBody(PARAM_BCC, bccs[i], ContentType.create(TEXT_PLAIN, UTF_8)); - // Files - if (email.getAttachments().size() > 0) { - Iterator it = email.getAttachments().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - builder.addBinaryBody(String.format(PARAM_FILES, entry.getKey()), (InputStream) entry.getValue()); - } - } - - if (email.getContentIds().size() > 0) { - Iterator it = email.getContentIds().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - builder.addTextBody(String.format(PARAM_CONTENTS, entry.getKey()), (String) entry.getValue()); - } - } - - if (email.getHeaders().size() > 0) - builder.addTextBody(PARAM_HEADERS, new JSONObject(email.getHeaders()).toString(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getFrom() != null && !email.getFrom().isEmpty()) - builder.addTextBody(PARAM_FROM, email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getFromName() != null && !email.getFromName().isEmpty()) - builder.addTextBody(PARAM_FROMNAME, email.getFromName(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getReplyTo() != null && !email.getReplyTo().isEmpty()) - builder.addTextBody(PARAM_REPLYTO, email.getReplyTo(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getSubject() != null && !email.getSubject().isEmpty()) - builder.addTextBody(PARAM_SUBJECT, email.getSubject(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getHtml() != null && !email.getHtml().isEmpty()) - builder.addTextBody(PARAM_HTML, email.getHtml(), ContentType.create(TEXT_PLAIN, UTF_8)); - - if (email.getText() != null && !email.getText().isEmpty()) - builder.addTextBody(PARAM_TEXT, email.getText(), ContentType.create(TEXT_PLAIN, UTF_8)); - - String tmpString = email.smtpapi.jsonString(); - if (!tmpString.equals("{}")) - builder.addTextBody(PARAM_XSMTPAPI, tmpString, ContentType.create(TEXT_PLAIN, UTF_8)); - - return builder.build(); - } - - public SendGrid.Response send(Email email) throws SendGridException { - HttpPost httppost = new HttpPost(this.url + this.endpoint); - httppost.setEntity(this.buildBody(email)); - - // Using an API key - if (this.username == null) { - httppost.setHeader("Authorization", "Bearer " + this.password); - } - - try { - HttpResponse res = this.client.execute(httppost); - return new SendGrid.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity())); - } catch (IOException e) { - throw new SendGridException(e); - } - - } - - public static class Email { - private SMTPAPI smtpapi; - private ArrayList to; - private ArrayList toname; - private ArrayList cc; - private String from; - private String fromname; - private String replyto; - private String subject; - private String text; - private String html; - private ArrayList bcc; - private Map attachments; - private Map contents; - private Map headers; - - public Email() { - this.smtpapi = new SMTPAPI(); - this.to = new ArrayList(); - this.toname = new ArrayList(); - this.cc = new ArrayList(); - this.bcc = new ArrayList(); - this.attachments = new HashMap(); - this.contents = new HashMap(); - this.headers = new HashMap(); - } - - public Email addTo(String to) { - this.to.add(to); - return this; - } - - public Email addTo(String[] tos) { - this.to.addAll(Arrays.asList(tos)); - return this; - } - - public Email addTo(String to, String name) { - this.addTo(to); - return this.addToName(name); - } - - public Email setTo(String[] tos) { - this.to = new ArrayList(Arrays.asList(tos)); - return this; - } - - public String[] getTos() { - return this.to.toArray(new String[this.to.size()]); - } - - public Email addSmtpApiTo(String to) { - this.smtpapi.addTo(to); - return this; - } - - public Email addSmtpApiTo(String[] to) { - this.smtpapi.addTos(to); - return this; - } - - public Email addToName(String toname) { - this.toname.add(toname); - return this; - } - - public Email addToName(String[] tonames) { - this.toname.addAll(Arrays.asList(tonames)); - return this; - } - - public Email setToName(String[] tonames) { - this.toname = new ArrayList(Arrays.asList(tonames)); - return this; - } - - public String[] getToNames() { - return this.toname.toArray(new String[this.toname.size()]); - } - - public Email addCc(String cc) { - this.cc.add(cc); - return this; - } - - public Email addCc(String[] ccs) { - this.cc.addAll(Arrays.asList(ccs)); - return this; - } - - public Email setCc(String[] ccs) { - this.cc = new ArrayList(Arrays.asList(ccs)); - return this; - } - - public String[] getCcs() { - return this.cc.toArray(new String[this.cc.size()]); - } - - public Email setFrom(String from) { - this.from = from; - return this; - } - - public String getFrom() { - return this.from; - } - - public Email setFromName(String fromname) { - this.fromname = fromname; - return this; - } - - public String getFromName() { - return this.fromname; - } - - public Email setReplyTo(String replyto) { - this.replyto = replyto; - return this; - } - - public String getReplyTo() { - return this.replyto; - } - - public Email addBcc(String bcc) { - this.bcc.add(bcc); - return this; - } - - public Email addBcc(String[] bccs) { - this.bcc.addAll(Arrays.asList(bccs)); - return this; - } - - public Email setBcc(String[] bccs) { - this.bcc = new ArrayList(Arrays.asList(bccs)); - return this; - } - - public String[] getBccs() { - return this.bcc.toArray(new String[this.bcc.size()]); - } - - public Email setSubject(String subject) { - this.subject = subject; - return this; - } - - public String getSubject() { - return this.subject; - } - - public Email setText(String text) { - this.text = text; - return this; - } - - public String getText() { - return this.text; - } - - public Email setHtml(String html) { - this.html = html; - return this; - } - - public String getHtml() { - return this.html; - } - - public Email addSubstitution(String key, String[] val) { - this.smtpapi.addSubstitutions(key, val); - return this; - } - - public JSONObject getSubstitutions() { - return this.smtpapi.getSubstitutions(); - } - - public Email addUniqueArg(String key, String val) { - this.smtpapi.addUniqueArg(key, val); - return this; - } - - public JSONObject getUniqueArgs() { - return this.smtpapi.getUniqueArgs(); - } - - public Email addCategory(String category) { - this.smtpapi.addCategory(category); - return this; - } - - public String[] getCategories() { - return this.smtpapi.getCategories(); - } - - public Email addSection(String key, String val) { - this.smtpapi.addSection(key, val); - return this; - } - - public JSONObject getSections() { - return this.smtpapi.getSections(); - } - - public Email addFilter(String filter_name, String parameter_name, String parameter_value) { - this.smtpapi.addFilter(filter_name, parameter_name, parameter_value); - return this; - } - - public JSONObject getFilters() { - return this.smtpapi.getFilters(); - } - - public Email setASMGroupId(int val) { - this.smtpapi.setASMGroupId(val); - return this; - } - - public Integer getASMGroupId() { - return this.smtpapi.getASMGroupId(); - } - - public Email setSendAt(int sendAt) { - this.smtpapi.setSendAt(sendAt); - return this; - } - - public int getSendAt() { - return this.smtpapi.getSendAt(); - } - - /** - * Convenience method to set the template - * - * @param templateId The ID string of your template - * @return this - */ - public Email setTemplateId(String templateId) { - this.getSMTPAPI().addFilter("templates", "enable", 1); - this.getSMTPAPI().addFilter("templates", "template_id", templateId); - return this; - } - - public Email addAttachment(String name, File file) throws IOException, FileNotFoundException { - return this.addAttachment(name, new FileInputStream(file)); - } - - public Email addAttachment(String name, String file) throws IOException { - return this.addAttachment(name, new ByteArrayInputStream(file.getBytes())); - } - - public Email addAttachment(String name, InputStream file) throws IOException { - this.attachments.put(name, file); - return this; - } - - public Map getAttachments() { - return this.attachments; - } - - public Email addContentId(String attachmentName, String cid) { - this.contents.put(attachmentName, cid); - return this; - } - - public Map getContentIds() { - return this.contents; - } - - public Email addHeader(String key, String val) { - this.headers.put(key, val); - return this; - } - - public Map getHeaders() { - return this.headers; - } - - public SMTPAPI getSMTPAPI() { - return this.smtpapi; - } - } - - public static class Response { - private int code; - private boolean success; - private String message; - - public Response(int code, String msg) { - this.code = code; - this.success = code == 200; - this.message = msg; - } - - public int getCode() { - return this.code; - } - - public boolean getStatus() { - return this.success; - } - - public String getMessage() { - return this.message; - } - } +/** + * Class Twilio SendGrid allows for quick and easy access to the Twilio SendGrid API. + */ +public class SendGrid extends BaseInterface { + + /** + * Construct a new Twilio SendGrid API wrapper. + * + * @param apiKey is your Twilio SendGrid API Key: https://app.sendgrid.com/settings/api_keys + */ + public SendGrid(final String apiKey) { + initializeSendGrid(apiKey); + } + + /** + * Construct a new Twilio SendGrid API wrapper. + * + * @param apiKey is your Twilio SendGrid API Key: https://app.sendgrid.com/settings/api_keys + * @param test is true if you are unit testing + */ + public SendGrid(final String apiKey, final Boolean test) { + super(test); + initializeSendGrid(apiKey); + } + + /** + * Construct a new Twilio SendGrid API wrapper. + * + * @param apiKey is your Twilio SendGrid API Key: https://app.sendgrid.com/settings/api_keys + * @param client the Client to use (allows to customize its configuration) + */ + public SendGrid(final String apiKey, final Client client) { + super(client); + initializeSendGrid(apiKey); + } + + /** + * Initialize the client. + * + * @param apiKey the user's API key + */ + public void initializeSendGrid(final String apiKey) { + this.initialize("Bearer " + apiKey, "api.sendgrid.com"); + } } diff --git a/src/main/java/com/sendgrid/SendGridAPI.java b/src/main/java/com/sendgrid/SendGridAPI.java new file mode 100644 index 00000000..71b2c3cc --- /dev/null +++ b/src/main/java/com/sendgrid/SendGridAPI.java @@ -0,0 +1,92 @@ +package com.sendgrid; + +import java.io.IOException; +import java.util.Map; + +public interface SendGridAPI { + + /** + * Initialize the client. + * + * @param auth authorization header value + * @param host the base URL for the API + */ + void initialize(final String auth, final String host); + + /** + * Get the current library version. + * + * @return the current version + */ + String getLibraryVersion(); + + /** + * Get the API version. + * + * @return the current API version + */ + String getVersion(); + + /** + * Set the API version. + * + * @param version the new version + */ + void setVersion(final String version); + + /** + * Get the request headers. + * + * @return the request headers + */ + Map getRequestHeaders(); + + /** + * Add/update a request header. + * + * @param key the header key + * @param value the header value + * @return the new set of request headers + */ + Map addRequestHeader(final String key, final String value); + + /** + * Remove a request header. + * + * @param key the header key to remove + * @return the new set of request headers + */ + Map removeRequestHeader(final String key); + + /** + * Get the host. + * + * @return the host + */ + String getHost(); + + /** + * Set the host. + * + * @param host the new host + */ + void setHost(final String host); + + /** + * Makes the call to the Twilio SendGrid API, override this method for testing. + * + * @param request the request to make + * @return the response object + * @throws IOException in case of a network error + */ + Response makeCall(final Request request) throws IOException; + + /** + * Class api sets up the request to the Twilio SendGrid API, this is main interface. + * + * @param request the request object + * @return the response object + * @throws IOException in case of a network error + */ + Response api(final Request request) throws IOException; +} diff --git a/src/main/java/com/sendgrid/SendGridException.java b/src/main/java/com/sendgrid/SendGridException.java deleted file mode 100644 index 57b35b50..00000000 --- a/src/main/java/com/sendgrid/SendGridException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.sendgrid; - -public class SendGridException extends Exception { - public SendGridException(Exception e) { - super(e); - } -} diff --git a/src/main/java/com/sendgrid/TwilioEmail.java b/src/main/java/com/sendgrid/TwilioEmail.java new file mode 100644 index 00000000..d2c79503 --- /dev/null +++ b/src/main/java/com/sendgrid/TwilioEmail.java @@ -0,0 +1,50 @@ +package com.sendgrid; + +import org.apache.commons.codec.binary.Base64; + +/** + * This class allows you to quickly and easily send emails through Twilio + * SendGrid using Java. + */ +public class TwilioEmail extends BaseInterface { + + /** + * Construct a new Twilio SendGrid API wrapper. + * + * @param username your Twilio Email API key SID or Account SID + * @param password your Twilio Email API key secret or Account Auth Token + */ + public TwilioEmail(final String username, final String password) { + initialize(username, password); + } + + /** + * Construct a new Twilio SendGrid API wrapper. + * + * @param username your Twilio Email API key SID or Account SID + * @param password your Twilio Email API key secret or Account Auth Token + * @param client the Client to use (allows to customize its configuration) + */ + public TwilioEmail(final String username, final String password, final Client client) { + super(client); + initialize(username, password); + } + + /** + * Initialize the client. + * + * @param username your Twilio Email API key SID or Account SID + * @param password your Twilio Email API key secret or Account Auth Token + */ + public void initialize(final String username, final String password) { + super.initialize(getAuthString(username, password), "email.twilio.com"); + } + + private String getAuthString(final String username, final String password) { + final String credentials = username + ":" + password; + final byte[] encodedBytes = Base64.encodeBase64(credentials.getBytes()); + final String encoderString = new String(encodedBytes); + + return "Basic " + encoderString; + } +} diff --git a/src/main/java/com/sendgrid/helpers/README.md b/src/main/java/com/sendgrid/helpers/README.md new file mode 100644 index 00000000..b9128ff6 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/README.md @@ -0,0 +1,19 @@ +**This helper allows you to quickly and easily build a Mail object for sending email through Twilio SendGrid.** + +## Dependencies + +- [Jackson](https://github.com/FasterXML/jackson) + +# Quick Start + +Run the [example](../../../../../../examples/mail) (make sure you have set your environment variable to include your SENDGRID_API_KEY). + +```bash +cd examples/mail +javac -classpath ../../build/libs/sendgrid-4.2.1-jar.jar:. Example.java && java -classpath ../examples/jackson-core-2.9.9.jar:../../build/libs/sendgrid-4.1.0-jar.jar:. Example +``` + +## Usage + +- See the [example](../../../../../../examples/mail) for a complete working example. +- [Documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html) diff --git a/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhook.java b/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhook.java new file mode 100644 index 00000000..0898133b --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhook.java @@ -0,0 +1,90 @@ +package com.sendgrid.helpers.eventwebhook; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.*; +import java.security.interfaces.ECPublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +/** + * This class allows you to easily use the Event Webhook feature. Read the docs + * for more details: + * https://sendgrid.com/docs/for-developers/tracking-events/event. + */ +public class EventWebhook { + /** + * Convert the public key string to a ECPublicKey. + * + * @param publicKey: verification key under Mail Settings + * @return a public key using the ECDSA algorithm + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + * @throws InvalidKeySpecException + */ + public java.security.interfaces.ECPublicKey ConvertPublicKeyToECDSA(String publicKey) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { + byte[] publicKeyInBytes = Base64.getDecoder().decode(publicKey); + KeyFactory factory = KeyFactory.getInstance("ECDSA", "BC"); + return (ECPublicKey) factory.generatePublic(new X509EncodedKeySpec(publicKeyInBytes)); + } + + + /** + * Verify signed event webhook requests. + * + * @param publicKey: elliptic curve public key + * @param payload: event payload string in the request body + * @param signature: value obtained from the + * 'X-Twilio-Email-Event-Webhook-Signature' header + * @param timestamp: value obtained from the + * 'X-Twilio-Email-Event-Webhook-Timestamp' header + * @return true or false if signature is valid + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + * @throws InvalidKeyException + * @throws SignatureException + * @throws IOException + */ + public boolean VerifySignature(ECPublicKey publicKey, String payload, String signature, String timestamp) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException { + return VerifySignature(publicKey, payload.getBytes(), signature, timestamp); + } + + /** + * Verify signed event webhook requests. + * + * @param publicKey: elliptic curve public key + * @param payload: event payload bytes in the request body + * @param signature: value obtained from the + * 'X-Twilio-Email-Event-Webhook-Signature' header + * @param timestamp: value obtained from the + * 'X-Twilio-Email-Event-Webhook-Timestamp' header + * @return true or false if signature is valid + * @throws NoSuchAlgorithmException + * @throws NoSuchProviderException + * @throws InvalidKeyException + * @throws SignatureException + * @throws IOException + */ + public boolean VerifySignature(ECPublicKey publicKey, byte[] payload, String signature, String timestamp) + throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException { + + // prepend the payload with the timestamp + final ByteArrayOutputStream payloadWithTimestamp = new ByteArrayOutputStream(); + payloadWithTimestamp.write(timestamp.getBytes()); + payloadWithTimestamp.write(payload); + + // create the signature object + final Signature signatureObject = Signature.getInstance("SHA256withECDSA", "BC"); + signatureObject.initVerify(publicKey); + signatureObject.update(payloadWithTimestamp.toByteArray()); + + // decode the signature + final byte[] signatureInBytes = Base64.getDecoder().decode(signature); + + // verify the signature + return signatureObject.verify(signatureInBytes); + } +} diff --git a/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhookHeader.java b/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhookHeader.java new file mode 100644 index 00000000..7bdc422c --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/eventwebhook/EventWebhookHeader.java @@ -0,0 +1,20 @@ +package com.sendgrid.helpers.eventwebhook; + +/** + * This enum lists headers that get posted to the webhook. Read the docs for + * more details: https://sendgrid.com/docs/for-developers/tracking-events/event. + */ +public enum EventWebhookHeader { + SIGNATURE("X-Twilio-Email-Event-Webhook-Signature"), TIMESTAMP("X-Twilio-Email-Event-Webhook-Timestamp"); + + public final String name; + + EventWebhookHeader(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/main/java/com/sendgrid/helpers/ips/IPAddress.java b/src/main/java/com/sendgrid/helpers/ips/IPAddress.java new file mode 100644 index 00000000..e190cdb9 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/ips/IPAddress.java @@ -0,0 +1,120 @@ +package com.sendgrid.helpers.ips; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class IPAddress { + + /** + * An IP address. + */ + @JsonProperty("ip") + private String ip; + + /** + * The subusers that are able to send email from this IP. + */ + @JsonProperty("subusers") + private List subUsers; + + /** + * The reverse DNS record for this IP address. + */ + @JsonProperty("rdns") + private String rdns; + + /** + * The IP pools that this IP has been added to. + */ + @JsonProperty("pools") + private List pools; + + /** + * Indicates if this IP address is currently warming up. + */ + @JsonProperty("warmup") + private boolean warmup; + + /** + * The date that the IP address was entered into warmup. + */ + @JsonProperty("start_date") + private long startDate; + + /** + * Indicates if this IP address has been whitelabeled. + */ + @JsonProperty("whitelabeled") + private boolean whitelabeled; + + /** + * The date that the IP address was assigned to the user. + */ + @JsonProperty("assigned_at") + private long assignedAt; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public List getSubUsers() { + return subUsers; + } + + public void setSubUsers(List subUsers) { + this.subUsers = subUsers; + } + + public String getRdns() { + return rdns; + } + + public void setRdns(String rdns) { + this.rdns = rdns; + } + + public List getPools() { + return pools; + } + + public void setPools(List pools) { + this.pools = pools; + } + + public boolean isWarmup() { + return warmup; + } + + public void setWarmup(boolean warmup) { + this.warmup = warmup; + } + + public long getStartDate() { + return startDate; + } + + public void setStartDate(long startDate) { + this.startDate = startDate; + } + + public boolean isWhitelabeled() { + return whitelabeled; + } + + public void setWhitelabeled(boolean whitelabeled) { + this.whitelabeled = whitelabeled; + } + + public long getAssignedAt() { + return assignedAt; + } + + public void setAssignedAt(long assignedAt) { + this.assignedAt = assignedAt; + } +} diff --git a/src/main/java/com/sendgrid/helpers/ips/IPsHelper.java b/src/main/java/com/sendgrid/helpers/ips/IPsHelper.java new file mode 100644 index 00000000..038901e1 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/ips/IPsHelper.java @@ -0,0 +1,47 @@ +package com.sendgrid.helpers.ips; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; +import org.apache.http.HttpStatus; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Helper class for quick and easy access to the SendGrid IP Addresses API. + */ +public class IPsHelper { + + private static final String ALL_IPS_ENDPOINT = "ips"; + + /** + * Get a list of unassigned IP addresses. + * @param sendGrid a SendGrid client. + * @return a list of unassigned ip addresses if response status is ok (200), otherwise - null + * @throws IOException in case of a network error or json parse error. + */ + public static List getAllUnassignedIPs(SendGrid sendGrid) throws IOException { + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint(ALL_IPS_ENDPOINT); + + Response response = sendGrid.api(request); + if (response != null && response.getStatusCode() == HttpStatus.SC_OK) { + List unassignedIPs = new ArrayList<>(); + List ipAddressList = new ObjectMapper().readValue(response.getBody(), new TypeReference>() {}); + for (IPAddress ipAddress : ipAddressList) { + if (ipAddress.getSubUsers() == null || ipAddress.getSubUsers().size() == 0) { + unassignedIPs.add(ipAddress.getIp()); + } + } + return unassignedIPs; + } + return null; + } + +} diff --git a/src/main/java/com/sendgrid/helpers/mail/Mail.java b/src/main/java/com/sendgrid/helpers/mail/Mail.java new file mode 100644 index 00000000..ea2b9739 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/Mail.java @@ -0,0 +1,627 @@ +package com.sendgrid.helpers.mail; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.sendgrid.helpers.mail.objects.ASM; +import com.sendgrid.helpers.mail.objects.Attachments; +import com.sendgrid.helpers.mail.objects.Content; +import com.sendgrid.helpers.mail.objects.Email; +import com.sendgrid.helpers.mail.objects.MailSettings; +import com.sendgrid.helpers.mail.objects.Personalization; +import com.sendgrid.helpers.mail.objects.TrackingSettings; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Class Mail builds an object that sends an email through Twilio SendGrid. Note that this object is + * not thread safe. + */ +@JsonInclude(Include.NON_DEFAULT) +public class Mail { + + /** The email's from field. */ + @JsonProperty("from") + public Email from; + + /** + * The email's subject line. This is the global, or “message level”, subject of your email. This + * may be overridden by personalizations[x].subject. + */ + @JsonProperty("subject") + public String subject; + + /** + * The email's personalization. Each object within personalizations can be thought of as an + * envelope - it defines who should receive an individual message and how that message should be + * handled. + */ + @JsonProperty("personalizations") + public List personalization; + + /** The email's content. */ + @JsonProperty("content") + public List content; + + /** The email's attachments. */ + @JsonProperty("attachments") + public List attachments; + + /** The email's template ID. */ + @JsonProperty("template_id") + public String templateId; + + /** + * The email's sections. An object of key/value pairs that define block sections of code to be + * used as substitutions. + */ + @JsonProperty("sections") + public Map sections; + + /** The email's headers. */ + @JsonProperty("headers") + public Map headers; + + /** The email's categories. */ + @JsonProperty("categories") + public List categories; + + /** + * The email's custom arguments. Values that are specific to the entire send that will be carried + * along with the email and its activity data. Substitutions will not be made on custom arguments, + * so any string that is entered into this parameter will be assumed to be the custom argument + * that you would like to be used. This parameter is overridden by personalizations[x].custom_args + * if that parameter has been defined. Total custom args size may not exceed 10,000 bytes. + */ + @JsonProperty("custom_args") + public Map customArgs; + + /** + * A unix timestamp allowing you to specify when you want your email to be delivered. This may be + * overridden by the personalizations[x].send_at parameter. Scheduling more than 72 hours in + * advance is forbidden. + */ + @JsonProperty("send_at") + public long sendAt; + + /** + * This ID represents a batch of emails to be sent at the same time. Including a batch_id in your + * request allows you include this email in that batch, and also enables you to cancel or pause + * the delivery of that batch. For more information, see https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send. + */ + @JsonProperty("batch_id") + public String batchId; + + /** The email's unsubscribe handling object. */ + @JsonProperty("asm") + public ASM asm; + + /** The email's IP pool name. */ + @JsonProperty("ip_pool_name") + public String ipPoolId; + + /** The email's mail settings. */ + @JsonProperty("mail_settings") + public MailSettings mailSettings; + + /** The email's tracking settings. */ + @JsonProperty("tracking_settings") + public TrackingSettings trackingSettings; + + /** The email's reply to address. */ + @JsonProperty("reply_to") + public Email replyTo; + + private static final ObjectMapper SORTED_MAPPER = new ObjectMapper(); + + static { + SORTED_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + } + + private List addToList(T element, List defaultList) { + if (defaultList != null) { + defaultList.add(element); + return defaultList; + } else { + List list = new ArrayList(); + list.add(element); + return list; + } + } + + private Map addToMap(K key, V value, Map defaultMap) { + if (defaultMap != null) { + defaultMap.put(key, value); + return defaultMap; + } else { + Map map = new HashMap(); + map.put(key, value); + return map; + } + } + + /** Construct a new Mail object. */ + public Mail() { + return; + } + + /** + * Construct a new Mail object. + * + * @param from the email's from address. + * @param subject the email's subject line. + * @param to the email's recipient. + * @param content the email's content. + */ + public Mail(Email from, String subject, Email to, Content content) { + this.setFrom(from); + this.setSubject(subject); + Personalization personalization = new Personalization(); + personalization.addTo(to); + this.addPersonalization(personalization); + this.addContent(content); + } + + /** + * Get the email's from address. + * + * @return the email's from address. + */ + @JsonProperty("from") + public Email getFrom() { + return this.from; + } + + /** + * Set the email's from address. + * + * @param from the email's from address. + */ + public void setFrom(Email from) { + this.from = from; + } + + /** + * Get the email's subject line. + * + * @return the email's subject line. + */ + @JsonProperty("subject") + public String getSubject() { + return subject; + } + + /** + * Set the email's subject line. + * + * @param subject the email's subject line. + */ + public void setSubject(String subject) { + this.subject = subject; + } + + /** + * Get the email's unsubscribe handling object (ASM). + * + * @return the email's ASM. + */ + @JsonProperty("asm") + public ASM getASM() { + return asm; + } + + /** + * Set the email's unsubscribe handling object (ASM). + * + * @param asm the email's ASM. + */ + public void setASM(ASM asm) { + this.asm = asm; + } + + /** + * Get the email's personalizations. Content added to the returned list will be included when + * sent. + * + * @return the email's personalizations. + */ + @JsonProperty("personalizations") + public List getPersonalization() { + return personalization; + } + + /** + * Add a personalization to the email. + * + * @param personalization a personalization. + */ + public void addPersonalization(Personalization personalization) { + this.personalization = addToList(personalization, this.personalization); + } + + /** + * Get the email's content. Content added to the returned list will be included when sent. + * + * @return the email's content. + */ + @JsonProperty("content") + public List getContent() { + return content; + } + + /** + * Add content to this email. + * + * @param content content to add to this email. + */ + public void addContent(Content content) { + Content newContent = new Content(); + newContent.setType(content.getType()); + newContent.setValue(content.getValue()); + this.content = addToList(newContent, this.content); + } + + /** + * Get the email's attachments. Attachments added to the returned list will be included when + * sent. + * + * @return the email's attachments. + */ + @JsonProperty("attachments") + public List getAttachments() { + return attachments; + } + + /** + * Add attachments to the email. + * + * @param attachments attachments to add. + */ + public void addAttachments(Attachments attachments) { + Attachments newAttachment = new Attachments(); + newAttachment.setContent(attachments.getContent()); + newAttachment.setType(attachments.getType()); + newAttachment.setFilename(attachments.getFilename()); + newAttachment.setDisposition(attachments.getDisposition()); + newAttachment.setContentId(attachments.getContentId()); + this.attachments = addToList(newAttachment, this.attachments); + } + + /** + * Get the email's template ID. + * + * @return the email's template ID. + */ + @JsonProperty("template_id") + public String getTemplateId() { + return this.templateId; + } + + /** + * Set the email's template ID. + * + * @param templateId the email's template ID. + */ + public void setTemplateId(String templateId) { + this.templateId = templateId; + } + + /** + * Get the email's sections. Sections added to the returned list will be included when sent. + * + * @return the email's sections. + */ + @JsonProperty("sections") + public Map getSections() { + return sections; + } + + /** + * Add a section to the email. + * + * @param key the section's key. + * @param value the section's value. + */ + public void addSection(String key, String value) { + this.sections = addToMap(key, value, this.sections); + } + + /** + * Get the email's headers. Headers added to the returned list will be included when sent. + * + * @return the email's headers. + */ + @JsonProperty("headers") + public Map getHeaders() { + return headers; + } + + /** + * Add a header to the email. + * + * @param key the header's key. + * @param value the header's value. + */ + public void addHeader(String key, String value) { + this.headers = addToMap(key, value, this.headers); + } + + /** + * Get the email's categories. Categories added to the returned list will be included when sent. + * + * @return the email's categories. + */ + @JsonProperty("categories") + public List getCategories() { + return categories; + } + + /** + * Add a category to the email. + * + * @param category the category. + */ + public void addCategory(String category) { + this.categories = addToList(category, this.categories); + } + + /** + * Get the email's custom arguments. Custom arguments added to the returned list will be included + * when sent. + * + * @return the email's custom arguments. + */ + @JsonProperty("custom_args") + public Map getCustomArgs() { + return customArgs; + } + + /** + * Add a custom argument to the email. + * + * @param key argument's key. + * @param value the argument's value. + */ + public void addCustomArg(String key, String value) { + this.customArgs = addToMap(key, value, this.customArgs); + } + + /** + * Get the email's send at time (Unix timestamp). + * + * @return the email's send at time. + */ + @JsonProperty("send_at") + public long sendAt() { + return sendAt; + } + + /** + * Set the email's send at time (Unix timestamp). + * + * @param sendAt the send at time. + */ + public void setSendAt(long sendAt) { + this.sendAt = sendAt; + } + + /** + * Get the email's batch ID. + * + * @return the batch ID. + */ + @JsonProperty("batch_id") + public String getBatchId() { + return batchId; + } + + /** + * Set the email's batch ID. + * + * @param batchId the batch ID. + */ + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + /** + * Get the email's IP pool ID. + * + * @return the IP pool ID. + */ + @JsonProperty("ip_pool_name") + public String getIpPoolId() { + return ipPoolId; + } + + /** + * Set the email's IP pool ID. + * + * @param ipPoolId the IP pool ID. + */ + public void setIpPoolId(String ipPoolId) { + this.ipPoolId = ipPoolId; + } + + /** + * Get the email's settings. + * + * @return the settings. + */ + @JsonProperty("mail_settings") + public MailSettings getMailSettings() { + return mailSettings; + } + + /** + * Set the email's settings. + * + * @param mailSettings the settings. + */ + public void setMailSettings(MailSettings mailSettings) { + this.mailSettings = mailSettings; + } + + /** + * Get the email's tracking settings. + * + * @return the tracking settings. + */ + @JsonProperty("tracking_settings") + public TrackingSettings getTrackingSettings() { + return trackingSettings; + } + + /** + * Set the email's tracking settings. + * + * @param trackingSettings the tracking settings. + */ + public void setTrackingSettings(TrackingSettings trackingSettings) { + this.trackingSettings = trackingSettings; + } + + /** + * Get the email's reply to address. + * + * @return the reply to address. + */ + @JsonProperty("reply_to") + public Email getReplyto() { + return replyTo; + } + + /** + * Set the email's reply to address. + * + * @param replyTo the reply to address. + */ + public void setReplyTo(Email replyTo) { + this.replyTo = replyTo; + } + + /** + * Create a string representation of the Mail object JSON. + * + * @return a JSON string. + * @throws IOException in case of a JSON marshal error. + */ + public String build() throws IOException { + try { + //ObjectMapper mapper = new ObjectMapper(); + return SORTED_MAPPER.writeValueAsString(this); + } catch (IOException ex) { + throw ex; + } + } + + /** + * Create a string representation of the Mail object JSON and pretty print it. + * + * @return a pretty JSON string. + * @throws IOException in case of a JSON marshal error. + */ + public String buildPretty() throws IOException { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); + } catch (IOException ex) { + throw ex; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((batchId == null) ? 0 : batchId.hashCode()); + result = prime * result + ((categories == null) ? 0 : categories.hashCode()); + result = prime * result + ((customArgs == null) ? 0 : customArgs.hashCode()); + result = prime * result + ((headers == null) ? 0 : headers.hashCode()); + result = prime * result + ((ipPoolId == null) ? 0 : ipPoolId.hashCode()); + result = prime * result + ((sections == null) ? 0 : sections.hashCode()); + result = prime * result + (int) (sendAt ^ (sendAt >>> 32)); + result = prime * result + ((subject == null) ? 0 : subject.hashCode()); + result = prime * result + ((templateId == null) ? 0 : templateId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Mail other = (Mail) obj; + if (batchId == null) { + if (other.batchId != null) { + return false; + } + } else if (!batchId.equals(other.batchId)) { + return false; + } + if (categories == null) { + if (other.categories != null) { + return false; + } + } else if (!categories.equals(other.categories)) { + return false; + } + if (customArgs == null) { + if (other.customArgs != null) { + return false; + } + } else if (!customArgs.equals(other.customArgs)) { + return false; + } + if (headers == null) { + if (other.headers != null) { + return false; + } + } else if (!headers.equals(other.headers)) { + return false; + } + if (ipPoolId == null) { + if (other.ipPoolId != null) { + return false; + } + } else if (!ipPoolId.equals(other.ipPoolId)) { + return false; + } + if (sections == null) { + if (other.sections != null) { + return false; + } + } else if (!sections.equals(other.sections)) { + return false; + } + if (sendAt != other.sendAt) { + return false; + } + if (subject == null) { + if (other.subject != null) { + return false; + } + } else if (!subject.equals(other.subject)) { + return false; + } + if (templateId == null) { + if (other.templateId != null) { + return false; + } + } else if (!templateId.equals(other.templateId)) { + return false; + } + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/ASM.java b/src/main/java/com/sendgrid/helpers/mail/objects/ASM.java new file mode 100644 index 00000000..44ce4228 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/ASM.java @@ -0,0 +1,64 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Arrays; + +@JsonInclude(Include.NON_DEFAULT) +public class ASM { + + @JsonProperty("group_id") + private int groupId; + + @JsonProperty("groups_to_display") + private int[] groupsToDisplay; + + @JsonProperty("group_id") + public int getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } + + @JsonProperty("groups_to_display") + public int[] getGroupsToDisplay() { + return groupsToDisplay; + } + + public void setGroupsToDisplay(int[] groupsToDisplay) { + this.groupsToDisplay = Arrays.copyOf(groupsToDisplay, groupsToDisplay.length); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + groupId; + result = prime * result + Arrays.hashCode(groupsToDisplay); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ASM other = (ASM) obj; + if (groupId != other.groupId) { + return false; + } + if (!Arrays.equals(groupsToDisplay, other.groupsToDisplay)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/Attachments.java b/src/main/java/com/sendgrid/helpers/mail/objects/Attachments.java new file mode 100644 index 00000000..873475d7 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/Attachments.java @@ -0,0 +1,319 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonIgnoreType; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.codec.binary.Base64; + +/** + * An attachment object. + */ +@JsonInclude(Include.NON_DEFAULT) +public class Attachments { + + /** The attachment content. */ + @JsonProperty("content") + private String content; + + /** + * The mime type of the content you are attaching. For example, “text/plain” or “text/html”. + */ + @JsonProperty("type") + private String type; + + /** The attachment file name. */ + @JsonProperty("filename") + private String filename; + + /** The attachment disposition. */ + @JsonProperty("disposition") + private String disposition; + + /** + * The attachment content ID. This is used when the disposition is set to “inline” and the + * attachment is an image, allowing the file to be displayed within the body of your email. + */ + @JsonProperty("content_id") + private String contentId; + + /** + * Get the attachment's content. + * + * @return the content. + */ + @JsonProperty("content") + public String getContent() { + return content; + } + + /** + * Set the attachment's content. + * + * @param content the content. + */ + public void setContent(String content) { + this.content = content; + } + + /** + * Get the mime type of the content you are attaching. For example, “text/plain” or “text/html”. + * + * @return the mime type. + */ + @JsonProperty("type") + public String getType() { + return type; + } + + /** + * Set the mime type of the content. + * + * @param type the mime type. + */ + public void setType(String type) { + this.type = type; + } + + /** + * Get the filename for this attachment. + * + * @return the file name. + */ + @JsonProperty("filename") + public String getFilename() { + return filename; + } + + /** + * Set the filename for this attachment. + * + * @param filename the filename. + */ + public void setFilename(String filename) { + this.filename = filename; + } + + /** + * Get the content-disposition of the attachment specifying how you would like the attachment to + * be displayed. For example, “inline” results in the attached file being displayed automatically + * within the message while “attachment” results in the attached file requiring some action to be + * taken before it is displayed (e.g. opening or downloading the file). + * + * @return the disposition. + */ + @JsonProperty("disposition") + public String getDisposition() { + return disposition; + } + + /** + * Set the content-disposition of the attachment. + * + * @param disposition the disposition. + */ + public void setDisposition(String disposition) { + this.disposition = disposition; + } + + /** + * Get the attachment content ID. This is used when the disposition is set to “inline” and the + * attachment is an image, allowing the file to be displayed within the body of your email. + * + * @return the content ID. + */ + @JsonProperty("content_id") + public String getContentId() { + return contentId; + } + + /** + * Set the content ID. + * + * @param contentId the content ID. + */ + public void setContentId(String contentId) { + this.contentId = contentId; + } + + /** + * A helper object to construct usable attachments. + */ + @JsonIgnoreType + public static class Builder { + + private static final int BYTE_BUFFER_SIZE = 4096; + + private String fileName; + private String content; + private String type; + private String disposition; + private String contentId; + + /** + * Construct a new attachment builder. + * + * @param fileName the filename to include. + * @param content an input stream for the content. + * @throws IllegalArgumentException in case either the fileName or the content is null. + */ + public Builder(String fileName, InputStream content) { + if (fileName == null) { + throw new IllegalArgumentException("File name mustn't be null"); + } + + if (content == null) { + throw new IllegalArgumentException("Content mustn't be null"); + } + + this.fileName = fileName; + this.content = encodeToBase64(content); + } + + /** + * Construct a new attachment builder. + * + * @param fileName the filename to include. + * @param content an input string for the content. + * @throws IllegalArgumentException in case either the fileName or the content is null. + */ + public Builder(String fileName, String content) { + if (fileName == null) { + throw new IllegalArgumentException("File name mustn't be null"); + } + + if (content == null) { + throw new IllegalArgumentException("Content mustn't be null"); + } + + this.fileName = fileName; + this.content = content; + } + + private String encodeToBase64(InputStream content) { + int read = 0; + byte[] bytes = new byte[BYTE_BUFFER_SIZE]; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + while ((read = content.read(bytes)) != -1) { + baos.write(bytes, 0, read); + } + + return Base64.encodeBase64String(baos.toByteArray()); + } catch (IOException e) { + throw new RuntimeException("Unable to convert content stream to base 64 encoded string", e); + } + } + + /** + * Set the type of this attachment builder. + * + * @param type the attachment type. + * @return attachment builder object. + */ + public Builder withType(String type) { + this.type = type; + return this; + } + + /** + * Set the disposition of this attachment builder. + * + * @param disposition the disposition. + * @return attachment builder object. + */ + public Builder withDisposition(String disposition) { + this.disposition = disposition; + return this; + } + + /** + * Set the content ID of this attachment builder. + * + * @param contentId the content ID. + * @return attachment builder object. + */ + public Builder withContentId(String contentId) { + this.contentId = contentId; + return this; + } + + /** + * Construct the attachments object. + * @return the attachments object constructed. + */ + public Attachments build() { + Attachments attachments = new Attachments(); + attachments.setContent(content); + attachments.setFilename(fileName); + attachments.setDisposition(disposition); + attachments.setContentId(contentId); + attachments.setType(type); + return attachments; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((content == null) ? 0 : content.hashCode()); + result = prime * result + ((contentId == null) ? 0 : contentId.hashCode()); + result = prime * result + ((disposition == null) ? 0 : disposition.hashCode()); + result = prime * result + ((filename == null) ? 0 : filename.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Attachments other = (Attachments) obj; + if (content == null) { + if (other.content != null) { + return false; + } + } else if (!content.equals(other.content)) { + return false; + } + if (contentId == null) { + if (other.contentId != null) { + return false; + } + } else if (!contentId.equals(other.contentId)) { + return false; + } + if (disposition == null) { + if (other.disposition != null) { + return false; + } + } else if (!disposition.equals(other.disposition)) { + return false; + } + if (filename == null) { + if (other.filename != null) { + return false; + } + } else if (!filename.equals(other.filename)) { + return false; + } + if (type == null) { + if (other.type != null) { + return false; + } + } else if (!type.equals(other.type)) { + return false; + } + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/BccSettings.java b/src/main/java/com/sendgrid/helpers/mail/objects/BccSettings.java new file mode 100644 index 00000000..68d7a535 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/BccSettings.java @@ -0,0 +1,71 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This object allows you to have a blind carbon copy automatically sent to the specified email + * address for every email that is sent. + */ +@JsonInclude(Include.NON_EMPTY) +public class BccSettings { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("email") + private String email; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("email") + public String getEmail() { + return this.email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + (enable ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BccSettings other = (BccSettings) obj; + if (email == null) { + if (other.email != null) { + return false; + } + } else if (!email.equals(other.email)) { + return false; + } + if (enable != other.enable) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/ClickTrackingSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/ClickTrackingSetting.java new file mode 100644 index 00000000..13ce3f13 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/ClickTrackingSetting.java @@ -0,0 +1,67 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Settings to determine how you would like to track the metrics of how your recipients interact + * with your email. + */ +@JsonInclude(Include.NON_EMPTY) +public class ClickTrackingSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("enable_text") + private boolean enableText; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("enable_text") + public boolean getEnableText() { + return enableText; + } + + public void setEnableText(boolean enableText) { + this.enableText = enableText; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + result = prime * result + (enableText ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ClickTrackingSetting other = (ClickTrackingSetting) obj; + if (enable != other.enable) { + return false; + } + if (enableText != other.enableText) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/Content.java b/src/main/java/com/sendgrid/helpers/mail/objects/Content.java new file mode 100644 index 00000000..1b333bfe --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/Content.java @@ -0,0 +1,72 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An object in which you may specify the content of your email. + */ +@JsonInclude(Include.NON_DEFAULT) +public class Content { + @JsonProperty("type") private String type; + @JsonProperty("value") private String value; + + public Content() { + return; + } + + public Content(String type, String value) { + this.setType(type); + this.setValue(value); + } + + @JsonProperty("type") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @JsonProperty("value") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Content other = (Content) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (value == null) { + if (other.value != null) + return false; + } else if (!value.equals(other.value)) + return false; + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/Email.java b/src/main/java/com/sendgrid/helpers/mail/objects/Email.java new file mode 100644 index 00000000..37e8fbcf --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/Email.java @@ -0,0 +1,84 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_DEFAULT) +public class Email { + + @JsonProperty("name") + private String name; + + @JsonProperty("email") + private String email; + + public Email() { + return; + } + + public Email(String email) { + this.setEmail(email); + } + + public Email(String email, String name) { + this.setEmail(email); + this.setName(name); + } + + @JsonProperty("name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonProperty("email") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Email other = (Email) obj; + if (email == null) { + if (other.email != null) { + return false; + } + } else if (!email.equals(other.email)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/FooterSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/FooterSetting.java new file mode 100644 index 00000000..6ec12eb2 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/FooterSetting.java @@ -0,0 +1,90 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An object representing the default footer that you would like included on every email. + */ +@JsonInclude(Include.NON_EMPTY) +public class FooterSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("text") + private String text; + + @JsonProperty("html") + private String html; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("text") + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @JsonProperty("html") + public String getHtml() { + return html; + } + + public void setHtml(String html) { + this.html = html; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + result = prime * result + ((html == null) ? 0 : html.hashCode()); + result = prime * result + ((text == null) ? 0 : text.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + FooterSetting other = (FooterSetting) obj; + if (enable != other.enable) { + return false; + } + if (html == null) { + if (other.html != null) { + return false; + } + } else if (!html.equals(other.html)) { + return false; + } + if (text == null) { + if (other.text != null) { + return false; + } + } else if (!text.equals(other.text)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/GoogleAnalyticsSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/GoogleAnalyticsSetting.java new file mode 100644 index 00000000..e8f12f70 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/GoogleAnalyticsSetting.java @@ -0,0 +1,150 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An object configuring the tracking provided by Google Analytics. + */ +@JsonInclude(Include.NON_EMPTY) +public class GoogleAnalyticsSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("utm_source") + private String campaignSource; + + @JsonProperty("utm_term") + private String campaignTerm; + + @JsonProperty("utm_content") + private String campaignContent; + + @JsonProperty("utm_campaign") + private String campaignName; + + @JsonProperty("utm_medium") + private String campaignMedium; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("utm_source") + public String getCampaignSource() { + return campaignSource; + } + + public void setCampaignSource(String campaignSource) { + this.campaignSource = campaignSource; + } + + @JsonProperty("utm_term") + public String getCampaignTerm() { + return campaignTerm; + } + + public void setCampaignTerm(String campaignTerm) { + this.campaignTerm = campaignTerm; + } + + @JsonProperty("utm_content") + public String getCampaignContent() { + return campaignContent; + } + + public void setCampaignContent(String campaignContent) { + this.campaignContent = campaignContent; + } + + @JsonProperty("utm_campaign") + public String getCampaignName() { + return campaignName; + } + + public void setCampaignName(String campaignName) { + this.campaignName = campaignName; + } + + @JsonProperty("utm_medium") + public String getCampaignMedium() { + return campaignMedium; + } + + public void setCampaignMedium(String campaignMedium) { + this.campaignMedium = campaignMedium; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((campaignContent == null) ? 0 : campaignContent.hashCode()); + result = prime * result + ((campaignMedium == null) ? 0 : campaignMedium.hashCode()); + result = prime * result + ((campaignName == null) ? 0 : campaignName.hashCode()); + result = prime * result + ((campaignSource == null) ? 0 : campaignSource.hashCode()); + result = prime * result + ((campaignTerm == null) ? 0 : campaignTerm.hashCode()); + result = prime * result + (enable ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + GoogleAnalyticsSetting other = (GoogleAnalyticsSetting) obj; + if (campaignContent == null) { + if (other.campaignContent != null) { + return false; + } + } else if (!campaignContent.equals(other.campaignContent)) { + return false; + } + if (campaignMedium == null) { + if (other.campaignMedium != null) { + return false; + } + } else if (!campaignMedium.equals(other.campaignMedium)) { + return false; + } + if (campaignName == null) { + if (other.campaignName != null) { + return false; + } + } else if (!campaignName.equals(other.campaignName)) { + return false; + } + if (campaignSource == null) { + if (other.campaignSource != null) { + return false; + } + } else if (!campaignSource.equals(other.campaignSource)) { + return false; + } + if (campaignTerm == null) { + if (other.campaignTerm != null) { + return false; + } + } else if (!campaignTerm.equals(other.campaignTerm)) { + return false; + } + if (enable != other.enable) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/MailSettings.java b/src/main/java/com/sendgrid/helpers/mail/objects/MailSettings.java new file mode 100644 index 00000000..1bad6b09 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/MailSettings.java @@ -0,0 +1,274 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An object representing a collection of different mail settings that you can use to specify how + * you would like this email to be handled. + */ + +@JsonInclude(Include.NON_DEFAULT) +public class MailSettings { + + @JsonProperty("bcc") + private BccSettings bccSettings; + + @JsonProperty("bypass_list_management") + private Setting bypassListManagement; + + @JsonProperty("bypass_spam_management") + private Setting bypassSpamManagement; + + @JsonProperty("bypass_bounce_management") + private Setting bypassBounceManagement; + + @JsonProperty("bypass_unsubscribe_management") + private Setting bypassUnsubscribeManagement; + + @JsonProperty("footer") + private FooterSetting footerSetting; + + @JsonProperty("sandbox_mode") + private Setting sandBoxMode; + + @JsonProperty("spam_check") + private SpamCheckSetting spamCheckSetting; + + @JsonProperty("bcc") + public BccSettings getBccSettings() { + return bccSettings; + } + + /** + * Set the BCC settings. + * + * @param bccSettings the BCC settings. + */ + public void setBccSettings(BccSettings bccSettings) { + this.bccSettings = bccSettings; + } + + /** + * A setting that allows you to bypass all unsubscribe groups and suppressions to ensure that the + * email is delivered to every single recipient. This should only be used in emergencies when it + * is absolutely necessary that every recipient receives your email. + * + * @return the bypass list setting. + */ + + @JsonProperty("bypass_list_management") + public Setting getBypassListManagement() { + return bypassListManagement; + } + + public void setBypassListManagement(Setting bypassListManagement) { + this.bypassListManagement = bypassListManagement; + } + + /** + * Allows you to bypass the spam report list to ensure that the email is delivered to recipients. + * Bounce and unsubscribe lists will still be checked; addresses on these other lists will not + * receive the message. + * + * This filter cannot be combined with the bypass_list_management filter. + * @return the bypass spam setting + */ + + @JsonProperty("bypass_spam_management") + public Setting getBypassSpamManagement() { + return bypassSpamManagement; + } + + public void setBypassSpamManagement(Setting bypassSpamManagement) { + this.bypassSpamManagement = bypassSpamManagement; + } + + /** + * Allows you to bypass the bounce list to ensure that the email is delivered to recipients. + * Spam report and unsubscribe lists will still be checked; addresses on these other lists + * will not receive the message. + * + * This filter cannot be combined with the bypass_list_management filter. + * @return the bypass bounce setting + */ + @JsonProperty("bypass_bounce_management") + public Setting getBypassBounceManagement() { + return bypassBounceManagement; + } + public void setBypassBounceManagement(Setting bypassBounceManagement) { + this.bypassBounceManagement = bypassBounceManagement; + } + + /** + * Allows you to bypass the global unsubscribe list to ensure that the email is delivered + * to recipients. Bounce and spam report lists will still be checked; addresses on these + * other lists will not receive the message. This filter applies only to global unsubscribes + * and will not bypass group unsubscribes. + * + * This filter cannot be combined with the bypass_list_management filter. + * @return the bypass unsubscribe setting + */ + @JsonProperty("bypass_unsubscribe_management") + public Setting getBypassUnsubscribeManagement() { + return bypassUnsubscribeManagement; + } + + public void setBypassUnsubscribeManagement(Setting bypassUnsubscribeManagement) { + this.bypassUnsubscribeManagement = bypassUnsubscribeManagement; + } + + /** + * Get the footer settings that you would like included on every email. + * + * @return the setting. + */ + + @JsonProperty("footer") + public FooterSetting getFooterSetting() { + return footerSetting; + } + + /** + * Set the footer settings that you would like included on every email. + * + * @param footerSetting the setting. + */ + public void setFooterSetting(FooterSetting footerSetting) { + this.footerSetting = footerSetting; + } + + /** + * Get sandbox mode. This allows you to send a test email to ensure that your request body is + * valid and formatted correctly. + * + * @return the sandbox mode setting. + */ + + @JsonProperty("sandbox_mode") + public Setting getSandBoxMode() { + return sandBoxMode; + } + + /** + * Set sandbox mode. + * + * @param sandBoxMode the sandbox mode setting. + */ + @JsonProperty("sandbox_mode") + public void setSandboxMode(Setting sandBoxMode) { + this.sandBoxMode = sandBoxMode; + } + + /** + * Get the spam check setting. This allows you to test the content of your email for spam. + * + * @return the spam check setting. + */ + + @JsonProperty("spam_check") + public SpamCheckSetting getSpamCheck() { + return spamCheckSetting; + } + + /** + * Set the spam check setting. This allows you to test the content of your email for spam. + * + * @param spamCheckSetting the spam check setting. + */ + + public void setSpamCheckSetting(SpamCheckSetting spamCheckSetting) { + this.spamCheckSetting = spamCheckSetting; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((bccSettings == null) ? 0 : bccSettings.hashCode()); + result = + prime * result + ((bypassListManagement == null) ? 0 : bypassListManagement.hashCode()); + result = + prime * result + ((bypassSpamManagement == null) ? 0 : bypassSpamManagement.hashCode()); + result = + prime * result + ((bypassBounceManagement == null) ? 0 : bypassBounceManagement.hashCode()); + result = + prime * result + ((bypassUnsubscribeManagement == null) ? 0 : bypassUnsubscribeManagement.hashCode()); + result = prime * result + ((footerSetting == null) ? 0 : footerSetting.hashCode()); + result = prime * result + ((sandBoxMode == null) ? 0 : sandBoxMode.hashCode()); + result = prime * result + ((spamCheckSetting == null) ? 0 : spamCheckSetting.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MailSettings other = (MailSettings) obj; + if (bccSettings == null) { + if (other.bccSettings != null) { + return false; + } + } else if (!bccSettings.equals(other.bccSettings)) { + return false; + } + if (bypassListManagement == null) { + if (other.bypassListManagement != null) { + return false; + } + } else if (!bypassListManagement.equals(other.bypassListManagement)) { + return false; + } + if (bypassSpamManagement == null) { + if (other.bypassSpamManagement != null) { + return false; + } + } else if (!bypassSpamManagement.equals(other.bypassSpamManagement)) { + return false; + } + if (bypassBounceManagement == null) { + if (other.bypassBounceManagement != null) { + return false; + } + } else if (!bypassBounceManagement.equals(other.bypassBounceManagement)) { + return false; + } + if (bypassUnsubscribeManagement == null) { + if (other.bypassUnsubscribeManagement != null) { + return false; + } + } else if (!bypassUnsubscribeManagement.equals(other.bypassUnsubscribeManagement)) { + return false; + } + if (footerSetting == null) { + if (other.footerSetting != null) { + return false; + } + } else if (!footerSetting.equals(other.footerSetting)) { + return false; + } + if (sandBoxMode == null) { + if (other.sandBoxMode != null) { + return false; + } + } else if (!sandBoxMode.equals(other.sandBoxMode)) { + return false; + } + if (spamCheckSetting == null) { + if (other.spamCheckSetting != null) { + return false; + } + } else if (!spamCheckSetting.equals(other.spamCheckSetting)) { + return false; + } + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/OpenTrackingSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/OpenTrackingSetting.java new file mode 100644 index 00000000..a44cb8d8 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/OpenTrackingSetting.java @@ -0,0 +1,73 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An open tracking settings object. This allows you to track whether the email was opened or not, + * but including a single pixel image in the body of the content. When the pixel is loaded, we can + * log that the email was opened. + */ +@JsonInclude(Include.NON_EMPTY) +public class OpenTrackingSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("substitution_tag") + private String substitutionTag; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("substitution_tag") + public String getSubstitutionTag() { + return substitutionTag; + } + + public void setSubstitutionTag(String substitutionTag) { + this.substitutionTag = substitutionTag; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + result = prime * result + ((substitutionTag == null) ? 0 : substitutionTag.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + OpenTrackingSetting other = (OpenTrackingSetting) obj; + if (enable != other.enable) { + return false; + } + if (substitutionTag == null) { + if (other.substitutionTag != null) { + return false; + } + } else if (!substitutionTag.equals(other.substitutionTag)) { + return false; + } + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/Personalization.java b/src/main/java/com/sendgrid/helpers/mail/objects/Personalization.java new file mode 100644 index 00000000..16e99005 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/Personalization.java @@ -0,0 +1,284 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@JsonInclude(Include.NON_DEFAULT) +public class Personalization { + + @JsonProperty("to") + private List tos; + + @JsonProperty("from") + private Email from; + + @JsonProperty("cc") + private List ccs; + + @JsonProperty("bcc") + private List bccs; + + @JsonProperty("subject") + private String subject; + + @JsonProperty("headers") + private Map headers; + + @JsonProperty("substitutions") + private Map substitutions; + + @JsonProperty("custom_args") + private Map customArgs; + + @JsonProperty("dynamic_template_data") + private Map dynamicTemplateData; + + @JsonProperty("send_at") + private long sendAt; + + @JsonProperty("to") + public List getTos() { + if (tos == null) { + return Collections.emptyList(); + } + return tos; + } + + public void addTo(Email email) { + Email newEmail = new Email(); + newEmail.setName(email.getName()); + newEmail.setEmail(email.getEmail()); + if (tos == null) { + tos = new ArrayList(); + tos.add(newEmail); + } else { + tos.add(newEmail); + } + } + + @JsonProperty("from") + public Email getFrom() { + return from; + } + + public void setFrom(Email email) { + this.from = email; + } + + @JsonProperty("cc") + public List getCcs() { + if (ccs == null) { + return Collections.emptyList(); + } + return ccs; + } + + public void addCc(Email email) { + Email newEmail = new Email(); + newEmail.setName(email.getName()); + newEmail.setEmail(email.getEmail()); + if (ccs == null) { + ccs = new ArrayList(); + ccs.add(newEmail); + } else { + ccs.add(newEmail); + } + } + + @JsonProperty("bcc") + public List getBccs() { + if (bccs == null) { + return Collections.emptyList(); + } + return bccs; + } + + public void addBcc(Email email) { + Email newEmail = new Email(); + newEmail.setName(email.getName()); + newEmail.setEmail(email.getEmail()); + if (bccs == null) { + bccs = new ArrayList(); + bccs.add(newEmail); + } else { + bccs.add(newEmail); + } + } + + @JsonProperty("subject") + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + @JsonProperty("headers") + public Map getHeaders() { + if (headers == null) { + return Collections.emptyMap(); + } + return headers; + } + + public void addHeader(String key, String value) { + if (headers == null) { + headers = new HashMap(); + headers.put(key, value); + } else { + headers.put(key, value); + } + } + + @JsonProperty("substitutions") + public Map getSubstitutions() { + if (substitutions == null) { + return Collections.emptyMap(); + } + return substitutions; + } + + public void addSubstitution(String key, String value) { + if (substitutions == null) { + substitutions = new HashMap(); + substitutions.put(key, value); + } else { + substitutions.put(key, value); + } + } + + @JsonProperty("custom_args") + public Map getCustomArgs() { + if (customArgs == null) { + return Collections.emptyMap(); + } + return customArgs; + } + + public void addCustomArg(String key, String value) { + if (customArgs == null) { + customArgs = new HashMap(); + customArgs.put(key, value); + } else { + customArgs.put(key, value); + } + } + + @JsonProperty("send_at") + public long sendAt() { + return sendAt; + } + + public void setSendAt(long sendAt) { + this.sendAt = sendAt; + } + + @JsonProperty("dynamic_template_data") + public Map getDynamicTemplateData() { + return dynamicTemplateData == null + ? Collections.emptyMap() : dynamicTemplateData; + } + + public void addDynamicTemplateData(String key, Object value) { + if (dynamicTemplateData == null) { + dynamicTemplateData = new HashMap(); + } + dynamicTemplateData.put(key, value); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((bccs == null) ? 0 : bccs.hashCode()); + result = prime * result + ((ccs == null) ? 0 : ccs.hashCode()); + result = prime * result + ((customArgs == null) ? 0 : customArgs.hashCode()); + result = prime * result + ((headers == null) ? 0 : headers.hashCode()); + result = prime * result + (int) (sendAt ^ (sendAt >>> 32)); + result = prime * result + ((subject == null) ? 0 : subject.hashCode()); + result = prime * result + ((substitutions == null) ? 0 : substitutions.hashCode()); + result = prime * result + ((tos == null) ? 0 : tos.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Personalization other = (Personalization) obj; + if (bccs == null) { + if (other.bccs != null) { + return false; + } + } else if (!bccs.equals(other.bccs)) { + return false; + } + if (ccs == null) { + if (other.ccs != null) { + return false; + } + } else if (!ccs.equals(other.ccs)) { + return false; + } + if (customArgs == null) { + if (other.customArgs != null) { + return false; + } + } else if (!customArgs.equals(other.customArgs)) { + return false; + } + if (headers == null) { + if (other.headers != null) { + return false; + } + } else if (!headers.equals(other.headers)) { + return false; + } + if (sendAt != other.sendAt) { + return false; + } + if (subject == null) { + if (other.subject != null) { + return false; + } + } else if (!subject.equals(other.subject)) { + return false; + } + if (substitutions == null) { + if (other.substitutions != null) { + return false; + } + } else if (!substitutions.equals(other.substitutions)) { + return false; + } + if (tos == null) { + if (other.tos != null) { + return false; + } + } else if (!tos.equals(other.tos)) { + return false; + } + if (from == null) { + if (other.from != null) { + return false; + } + } else if (!from.equals(other.from)) { + return false; + } + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/Setting.java b/src/main/java/com/sendgrid/helpers/mail/objects/Setting.java new file mode 100644 index 00000000..ab5aeca7 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/Setting.java @@ -0,0 +1,47 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_NULL) +public class Setting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Setting other = (Setting) obj; + if (enable != other.enable) { + return false; + } + return true; + } +} diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/SpamCheckSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/SpamCheckSetting.java new file mode 100644 index 00000000..b0939bdb --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/SpamCheckSetting.java @@ -0,0 +1,86 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A setting object that allows you to test the content of your email for spam. + */ +@JsonInclude(Include.NON_EMPTY) +public class SpamCheckSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("threshold") + private int spamThreshold; + + @JsonProperty("post_to_url") + private String postToUrl; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("threshold") + public int getSpamThreshold() { + return spamThreshold; + } + + public void setSpamThreshold(int spamThreshold) { + this.spamThreshold = spamThreshold; + } + + @JsonProperty("post_to_url") + public String getPostToUrl() { + return postToUrl; + } + + public void setPostToUrl(String postToUrl) { + this.postToUrl = postToUrl; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + result = prime * result + ((postToUrl == null) ? 0 : postToUrl.hashCode()); + result = prime * result + spamThreshold; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SpamCheckSetting other = (SpamCheckSetting) obj; + if (enable != other.enable) { + return false; + } + if (postToUrl == null) { + if (other.postToUrl != null) { + return false; + } + } else if (!postToUrl.equals(other.postToUrl)) { + return false; + } + if (spamThreshold != other.spamThreshold) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/SubscriptionTrackingSetting.java b/src/main/java/com/sendgrid/helpers/mail/objects/SubscriptionTrackingSetting.java new file mode 100644 index 00000000..fe0f102e --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/SubscriptionTrackingSetting.java @@ -0,0 +1,112 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A subscription tracking setting object. Subscription tracking allows you to insert a subscription + * management link at the bottom of the text and html bodies of your email. If you would like to + * specify the location of the link within your email, you may use the substitution_tag. + */ +@JsonInclude(Include.NON_EMPTY) +public class SubscriptionTrackingSetting { + + @JsonProperty("enable") + private boolean enable; + + @JsonProperty("text") + private String text; + + @JsonProperty("html") + private String html; + + @JsonProperty("substitution_tag") + private String substitutionTag; + + @JsonProperty("enable") + public boolean getEnable() { + return enable; + } + + public void setEnable(boolean enable) { + this.enable = enable; + } + + @JsonProperty("text") + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @JsonProperty("html") + public String getHtml() { + return html; + } + + public void setHtml(String html) { + this.html = html; + } + + @JsonProperty("substitution_tag") + public String getSubstitutionTag() { + return substitutionTag; + } + + public void setSubstitutionTag(String substitutionTag) { + this.substitutionTag = substitutionTag; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (enable ? 1231 : 1237); + result = prime * result + ((html == null) ? 0 : html.hashCode()); + result = prime * result + ((substitutionTag == null) ? 0 : substitutionTag.hashCode()); + result = prime * result + ((text == null) ? 0 : text.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SubscriptionTrackingSetting other = (SubscriptionTrackingSetting) obj; + if (enable != other.enable) { + return false; + } + if (html == null) { + if (other.html != null) { + return false; + } + } else if (!html.equals(other.html)) { + return false; + } + if (substitutionTag == null) { + if (other.substitutionTag != null) { + return false; + } + } else if (!substitutionTag.equals(other.substitutionTag)) { + return false; + } + if (text == null) { + if (other.text != null) { + return false; + } + } else if (!text.equals(other.text)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/sendgrid/helpers/mail/objects/TrackingSettings.java b/src/main/java/com/sendgrid/helpers/mail/objects/TrackingSettings.java new file mode 100644 index 00000000..08a9b411 --- /dev/null +++ b/src/main/java/com/sendgrid/helpers/mail/objects/TrackingSettings.java @@ -0,0 +1,115 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(Include.NON_DEFAULT) +public class TrackingSettings { + + @JsonProperty("click_tracking") + private ClickTrackingSetting clickTrackingSetting; + + @JsonProperty("open_tracking") + private OpenTrackingSetting openTrackingSetting; + + @JsonProperty("subscription_tracking") + private SubscriptionTrackingSetting subscriptionTrackingSetting; + + @JsonProperty("ganalytics") + private GoogleAnalyticsSetting googleAnalyticsSetting; + + @JsonProperty("click_tracking") + public ClickTrackingSetting getClickTrackingSetting() { + return clickTrackingSetting; + } + + public void setClickTrackingSetting(ClickTrackingSetting clickTrackingSetting) { + this.clickTrackingSetting = clickTrackingSetting; + } + + @JsonProperty("open_tracking") + public OpenTrackingSetting getOpenTrackingSetting() { + return openTrackingSetting; + } + + public void setOpenTrackingSetting(OpenTrackingSetting openTrackingSetting) { + this.openTrackingSetting = openTrackingSetting; + } + + @JsonProperty("subscription_tracking") + public SubscriptionTrackingSetting getSubscriptionTrackingSetting() { + return subscriptionTrackingSetting; + } + + public void setSubscriptionTrackingSetting( + SubscriptionTrackingSetting subscriptionTrackingSetting) { + this.subscriptionTrackingSetting = subscriptionTrackingSetting; + } + + @JsonProperty("ganalytics") + public GoogleAnalyticsSetting getGoogleAnalyticsSetting() { + return googleAnalyticsSetting; + } + + public void setGoogleAnalyticsSetting(GoogleAnalyticsSetting googleAnalyticsSetting) { + this.googleAnalyticsSetting = googleAnalyticsSetting; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = + prime * result + ((clickTrackingSetting == null) ? 0 : clickTrackingSetting.hashCode()); + result = + prime * result + ((googleAnalyticsSetting == null) ? 0 : googleAnalyticsSetting.hashCode()); + result = prime * result + ((openTrackingSetting == null) ? 0 : openTrackingSetting.hashCode()); + result = prime * result + ((subscriptionTrackingSetting == null) ? 0 + : subscriptionTrackingSetting.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TrackingSettings other = (TrackingSettings) obj; + if (clickTrackingSetting == null) { + if (other.clickTrackingSetting != null) { + return false; + } + } else if (!clickTrackingSetting.equals(other.clickTrackingSetting)) { + return false; + } + if (googleAnalyticsSetting == null) { + if (other.googleAnalyticsSetting != null) { + return false; + } + } else if (!googleAnalyticsSetting.equals(other.googleAnalyticsSetting)) { + return false; + } + if (openTrackingSetting == null) { + if (other.openTrackingSetting != null) { + return false; + } + } else if (!openTrackingSetting.equals(other.openTrackingSetting)) { + return false; + } + if (subscriptionTrackingSetting == null) { + if (other.subscriptionTrackingSetting != null) { + return false; + } + } else if (!subscriptionTrackingSetting.equals(other.subscriptionTrackingSetting)) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/src/test/java/com/sendgrid/LicenseTest.java b/src/test/java/com/sendgrid/LicenseTest.java new file mode 100644 index 00000000..1f96ef70 --- /dev/null +++ b/src/test/java/com/sendgrid/LicenseTest.java @@ -0,0 +1,28 @@ +package com.sendgrid; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Calendar; +import org.junit.Assert; +import org.junit.Test; + +public class LicenseTest { + + @Test + public void testLicenseShouldHaveCorrectYear() throws IOException { + String copyrightText = null; + try (BufferedReader br = new BufferedReader(new FileReader("./LICENSE"))) { + for (String line; (line = br.readLine()) != null; ) { + if (line.startsWith("Copyright")) { + copyrightText = line; + break; + } + } + } + String expectedCopyright = String + .format("Copyright (C) %d, Twilio SendGrid, Inc. ", + Calendar.getInstance().get(Calendar.YEAR)); + Assert.assertEquals("License has incorrect year", copyrightText, expectedCopyright); + } +} diff --git a/src/test/java/com/sendgrid/MockSendGrid.java b/src/test/java/com/sendgrid/MockSendGrid.java new file mode 100644 index 00000000..35f65ae1 --- /dev/null +++ b/src/test/java/com/sendgrid/MockSendGrid.java @@ -0,0 +1,28 @@ +package com.sendgrid; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class MockSendGrid extends SendGrid { + Request request; + + public MockSendGrid(String apiKey) { + super(apiKey); + } + + public Response makeCall(Request request) throws IOException { + this.request = request; + Response response = new Response(); + response.setStatusCode(200); + response.setBody("{\"message\":\"success\"}"); + Map headers = new HashMap<>(); + headers.put("Test", "Header"); + response.setHeaders(headers); + return response; + } + + public Request getRequest() { + return this.request; + } +} \ No newline at end of file diff --git a/src/test/java/com/sendgrid/SendGridTest.java b/src/test/java/com/sendgrid/SendGridTest.java index f9130bed..8737cbb2 100644 --- a/src/test/java/com/sendgrid/SendGridTest.java +++ b/src/test/java/com/sendgrid/SendGridTest.java @@ -1,230 +1,3291 @@ package com.sendgrid; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; +import org.junit.Assert; +import org.junit.Test; + import java.io.IOException; import java.util.HashMap; import java.util.Map; +import static org.mockito.Mockito.*; -import org.skyscreamer.jsonassert.JSONAssert; +public class SendGridTest { -import org.json.JSONObject; -import org.junit.Test; + private final String SENDGRID_API_KEY = ""; -import static org.junit.Assert.*; + public Map buildDefaultHeaders() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + Map requestHeaders = new HashMap(); + requestHeaders.put("Authorization", "Bearer " + SENDGRID_API_KEY); + String USER_AGENT = "sendgrid/" + sg.getLibraryVersion() + ";java"; + requestHeaders.put("User-Agent", USER_AGENT); + requestHeaders.put("Accept", "application/json"); + return requestHeaders; + } -public class SendGridTest { - SendGrid.Email email; + @Test + public void testInitialization() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + Assert.assertEquals(sg.getHost(), "api.sendgrid.com"); + Assert.assertEquals(sg.getVersion(), "v3"); + Map requestHeaders = buildDefaultHeaders(); + Assert.assertEquals(sg.getRequestHeaders(), requestHeaders); + } - private static final String USERNAME = "USERNAME"; - private static final String PASSWORD = "PASSWORD"; + @Test + public void testConstructWithClient() throws IOException { + Client client = mock(Client.class); + SendGrid sg = new SendGrid(SENDGRID_API_KEY, client); + Request request = new Request(); + sg.makeCall(request); + verify(client).api(request); + } - @Test - public void testVersion() { - SendGrid client = new SendGrid(USERNAME, PASSWORD); - assertEquals(client.getVersion(), "2.2.2"); - } + @Test + public void testLibraryVersion() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + Assert.assertEquals(sg.getLibraryVersion(), "4.10.3"); + } + + @Test + public void testVersion() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setVersion("v4"); + Assert.assertEquals(sg.getVersion(), "v4"); + } + + @Test + public void testRequestHeaders() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + Map requestHeaders = buildDefaultHeaders(); + + sg.addRequestHeader("Test", "one"); + requestHeaders.put("Test", "one"); + Assert.assertEquals(sg.getRequestHeaders(), requestHeaders); + + sg.removeRequestHeader("Test"); + requestHeaders.remove("Test"); + Assert.assertEquals(sg.getRequestHeaders(), requestHeaders); + } + + @Test + public void testHost() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setHost("api.new.com"); + Assert.assertEquals(sg.getHost(), "api.new.com"); + } + + @Test + public void testRateLimitRetry() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setRateLimitRetry(100); + Assert.assertEquals(sg.getRateLimitRetry(), 100); + } + + @Test + public void testRateLimitSleep() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setRateLimitSleep(999); + Assert.assertEquals(sg.getRateLimitSleep(), 999); + } + + + @Test + public void test_async() { + final Object sync = new Object(); + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - @Test - public void testBuildGradleVersion() { - try { - SendGrid client = new SendGrid(USERNAME, PASSWORD); - BufferedReader br = new BufferedReader(new FileReader("./build.gradle")); - String line = br.readLine(); - String regex = "version\\s*=\\s*'" + client.getVersion() + "'"; - - while (line != null) { - if (line.matches(regex)) { - br.close(); - return; - } - line = br.readLine(); - } - br.close(); - fail("build.gradle version does not match"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + Request request = new Request(); + + request.setMethod(Method.GET); + request.setEndpoint("access_settings/activity"); + request.addQueryParam("limit", "1"); + sg.attempt(request, new APICallback() { + @Override + public void error(Exception e) { + Assert.fail(); + synchronized(sync) { + sync.notify(); } + } - } + @Override + public void response(Response response) { + Assert.assertEquals(200, response.getStatusCode()); + synchronized(sync) { + sync.notify(); + } + } + }); - @Test - public void testUsernamePasswordConstructor() { - SendGrid client = new SendGrid(USERNAME, PASSWORD); + try { + synchronized(sync) { + sync.wait(2000); + } + } catch(InterruptedException ex) { + Assert.fail(ex.toString()); } + } - @Test - public void testApiKeyConstructor() { - SendGrid client = new SendGrid(PASSWORD); - } + @Test + public void test_async_rate_limit() { + final Object sync = new Object(); + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "429"); - @Test - public void testAddTo() { - email = new SendGrid.Email(); + Request request = new Request(); - String address = "email@example.com"; - String address2 = "email2@example.com"; - email.addTo(address); - email.addTo(address2); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/activity"); + request.addQueryParam("limit", "1"); + sg.attempt(request, new APICallback() { + @Override + public void error(Exception e) { + Assert.assertEquals(e.getClass(), RateLimitException.class); + sync.notify(); + } - String[] correct = {address, address2}; + @Override + public void response(Response response) { + Assert.fail(); + sync.notify(); + } + }); - assertArrayEquals(correct, email.getTos()); + try { + synchronized(sync) { + sync.wait(2000); + } + } catch(InterruptedException ex) { + Assert.fail(ex.toString()); } + } - @Test - public void testAddToWithAFrom() { - email = new SendGrid.Email(); + @Test + public void test_access_settings_activity_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - String address = "email@example.com"; - String fromaddress = "from@mailinator.com"; - email.addTo(address); - email.setFrom(fromaddress); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/activity"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - String[] correct = {address}; + @Test + public void test_access_settings_whitelist_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - assertArrayEquals(correct, email.getTos()); - assertEquals(fromaddress, email.getFrom()); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("access_settings/whitelist"); + request.setBody("{\"ips\":[{\"ip\":\"192.168.1.1\"},{\"ip\":\"192.*.*.*\"},{\"ip\":\"192.168.1.3/32\"}]}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - } + @Test + public void test_access_settings_whitelist_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - @Test - public void testAddToName() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/whitelist"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - String name = "John"; - email.addToName(name); + @Test + public void test_access_settings_whitelist_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); - String[] correct = {name}; + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("access_settings/whitelist"); + request.setBody("{\"ids\":[1,2,3]}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } - assertArrayEquals(correct, email.getToNames()); - } + @Test + public void test_access_settings_whitelist__rule_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - @Test - public void testAddCc() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("access_settings/whitelist/{rule_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - String address = "email@example.com"; - email.addCc(address); + @Test + public void test_access_settings_whitelist__rule_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); - String[] correct = {address}; + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("access_settings/whitelist/{rule_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } - assertArrayEquals(correct, email.getCcs()); - } + @Test + public void test_alerts_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - @Test - public void testSetFrom() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("alerts"); + request.setBody("{\"type\":\"stats_notification\",\"frequency\":\"daily\",\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - String address = "email@example.com"; - email.setFrom(address); + @Test + public void test_alerts_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - assertEquals(address, email.getFrom()); - } + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - @Test - public void testSetFromName() { - email = new SendGrid.Email(); + @Test + public void test_alerts__alert_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - String fromname = "Uncle Bob"; - email.setFromName(fromname); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("alerts/{alert_id}"); + request.setBody("{\"email_to\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - assertEquals(fromname, email.getFromName()); - } + @Test + public void test_alerts__alert_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - @Test - public void testSetReplyTo() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - String address = "email@example.com"; - email.setReplyTo(address); + @Test + public void test_alerts__alert_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); - assertEquals(address, email.getReplyTo()); - } + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("alerts/{alert_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } - @Test - public void testAddBcc() { - email = new SendGrid.Email(); + @Test + public void test_api_keys_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - String address = "email@example.com"; - email.addBcc(address); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("api_keys"); + request.setBody("{\"sample\":\"data\",\"scopes\":[\"mail.send\",\"alerts.create\",\"alerts.read\"],\"name\":\"My API Key\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - String[] correct = {address}; + @Test + public void test_api_keys_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - assertArrayEquals(correct, email.getBccs()); - } + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - @Test - public void testSetSubject() { - email = new SendGrid.Email(); + @Test + public void test_api_keys__api_key_id__put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - String subject = "This is a subject"; - email.setSubject(subject); + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"scopes\":[\"user.profile.read\",\"user.profile.update\"],\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - assertEquals(subject, email.getSubject()); - } + @Test + public void test_api_keys__api_key_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - @Test - public void testSetText() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("api_keys/{api_key_id}"); + request.setBody("{\"name\":\"A New Hope\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - String text = "This is some email text."; - email.setText(text); + @Test + public void test_api_keys__api_key_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - assertEquals(text, email.getText()); - } + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - @Test - public void testSetHtml() { - email = new SendGrid.Email(); + @Test + public void test_api_keys__api_key_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); - String html = "This is some email text."; - email.setHtml(html); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("api_keys/{api_key_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } - assertEquals(html, email.getHtml()); - } + @Test + public void test_asm_groups_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - @Test - public void testAddHeader() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups"); + request.setBody("{\"is_default\":true,\"description\":\"Suggestions for products our users might like.\",\"name\":\"Product Suggestions\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - email.addHeader("key", "value"); - email.addHeader("other", "other-value"); + @Test + public void test_asm_groups_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - Map correct = new HashMap(); - correct.put("key", "value"); - correct.put("other", "other-value"); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups"); + request.addQueryParam("id", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - assertEquals(correct, email.getHeaders()); - } + @Test + public void test_asm_groups__group_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - @Test - public void testSetTemplateId() { - email = new SendGrid.Email(); - email.setTemplateId("abc-123"); + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("asm/groups/{group_id}"); + request.setBody("{\"description\":\"Suggestions for items our users might like.\",\"name\":\"Item Suggestions\",\"id\":103}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - String filters = email.getSMTPAPI().jsonString(); + @Test + public void test_asm_groups__group_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); - JSONObject obj = new JSONObject(); - obj.put("filters", new JSONObject().put("templates", new JSONObject() - .put("settings", new JSONObject().put("enable", 1) - .put("template_id", "abc-123")))); + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } - JSONAssert.assertEquals(filters, obj.toString(), false); - } + @Test + public void test_asm_groups__group_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); - @Test - public void testSmtpapiToHeader() { - email = new SendGrid.Email(); + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } - String[] expected = {"example@email.com"}; + @Test + public void test_asm_groups__group_id__suppressions_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); - email.getSMTPAPI().addTo(expected[0]); - String[] result = email.getSMTPAPI().getTos(); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } - assertArrayEquals(expected, result); - } + @Test + public void test_asm_groups__group_id__suppressions_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/groups/{group_id}/suppressions"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_asm_groups__group_id__suppressions_search_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/groups/{group_id}/suppressions/search"); + request.setBody("{\"recipient_emails\":[\"exists1@example.com\",\"exists2@example.com\",\"doesnotexists@example.com\"]}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_asm_groups__group_id__suppressions__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/groups/{group_id}/suppressions/{email}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_asm_suppressions_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_asm_suppressions_global_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("asm/suppressions/global"); + request.setBody("{\"recipient_emails\":[\"test1@example.com\",\"test2@example.com\"]}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_asm_suppressions_global__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_asm_suppressions_global__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("asm/suppressions/global/{email}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_asm_suppressions__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("asm/suppressions/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_browsers_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("browsers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("browsers", "test_string"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("offset", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns"); + request.setBody("{\"custom_unsubscribe_url\":\"\",\"html_content\":\"

Check out our spring line!

\",\"list_ids\":[110,124],\"sender_id\":124451,\"subject\":\"New Products for Spring!\",\"plain_content\":\"Check out our spring line!\",\"suppression_group_id\":42,\"title\":\"March Newsletter\",\"segment_ids\":[110],\"categories\":[\"spring line\"],\"ip_pool\":\"marketing\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_campaigns_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}"); + request.setBody("{\"html_content\":\"

Check out our summer line!

\",\"subject\":\"New Products for Summer!\",\"title\":\"May Newsletter\",\"categories\":[\"summer line\"],\"plain_content\":\"Check out our summer line!\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489451436}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + request.setBody("{\"send_at\":1489771528}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("campaigns/{campaign_id}/schedules"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_now_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/now"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_campaigns__campaign_id__schedules_test_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("campaigns/{campaign_id}/schedules/test"); + request.setBody("{\"to\":\"your.email@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_categories_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories"); + request.addQueryParam("category", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_categories_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("categories", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_categories_stats_sums_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("categories/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_clients_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_clients__client_type__stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("clients/{client_type}/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_custom_fields_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/custom_fields"); + request.setBody("{\"type\":\"text\",\"name\":\"pet\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_custom_fields_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_custom_fields__custom_field_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_custom_fields__custom_field_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "202"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/custom_fields/{custom_field_id}"); + Response response = sg.api(request); + Assert.assertEquals(202, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists"); + request.setBody("{\"name\":\"your list name\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists"); + request.setBody("[1,2,3,4]"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/lists/{list_id}"); + request.setBody("{\"name\":\"newlistname\"}"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "202"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + Assert.assertEquals(202, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__recipients_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__recipients_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/lists/{list_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__recipients__recipient_id__post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_lists__list_id__recipients__recipient_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/lists/{list_id}/recipients/{recipient_id}"); + request.addQueryParam("recipient_id", "1"); + request.addQueryParam("list_id", "1"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"first_name\":\"Guy\",\"last_name\":\"Jones\",\"email\":\"jones@example.com\"}]"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/recipients"); + request.setBody("[{\"age\":25,\"last_name\":\"User\",\"email\":\"example@example.com\",\"first_name\":\"\"},{\"age\":25,\"last_name\":\"User\",\"email\":\"example2@example.com\",\"first_name\":\"Example\"}]"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients"); + request.setBody("[\"recipient_id1\",\"recipient_id2\"]"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_billable_count_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/billable_count"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_count_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/count"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients_search_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/search"); + request.addQueryParam("{field_name}", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients__recipient_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients__recipient_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/recipients/{recipient_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_contactdb_recipients__recipient_id__lists_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/recipients/{recipient_id}/lists"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_reserved_fields_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/reserved_fields"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("contactdb/segments"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and_or\":\"\",\"value\":\"Miller\"},{\"operator\":\"gt\",\"field\":\"last_clicked\",\"and_or\":\"and\",\"value\":\"01/02/2015\"},{\"operator\":\"eq\",\"field\":\"clicks.campaign_identifier\",\"and_or\":\"or\",\"value\":\"513\"}],\"name\":\"Last Name Miller\",\"list_id\":4}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments__segment_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.setBody("{\"conditions\":[{\"operator\":\"eq\",\"field\":\"last_name\",\"and_or\":\"\",\"value\":\"Miller\"}],\"name\":\"The Millers\",\"list_id\":5}"); + request.addQueryParam("segment_id", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments__segment_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("segment_id", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments__segment_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("contactdb/segments/{segment_id}"); + request.addQueryParam("delete_contacts", "true"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_contactdb_segments__segment_id__recipients_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("contactdb/segments/{segment_id}/recipients"); + request.addQueryParam("page", "1"); + request.addQueryParam("page_size", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_devices_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("devices/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_geo_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("geo/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("country", "US"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("exclude_whitelabels", "true"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_assigned_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/assigned"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_pools_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools"); + request.setBody("{\"name\":\"marketing\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_pools_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_pools__pool_name__put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("ips/pools/{pool_name}"); + request.setBody("{\"name\":\"new_pool_name\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_pools__pool_name__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_pools__pool_name__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_ips_pools__pool_name__ips_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/pools/{pool_name}/ips"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_ips_pools__pool_name__ips__ip__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/pools/{pool_name}/ips/{ip}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_ips_warmup_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("ips/warmup"); + request.setBody("{\"ip\":\"0.0.0.0\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_warmup_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_warmup__ip_address__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_ips_warmup__ip_address__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("ips/warmup/{ip_address}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_ips__ip_address__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("ips/{ip_address}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_batch_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/batch"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_mail_batch__batch_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail/batch/{batch_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_send_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "202"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\"[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"from\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"attachments\":[{\"name\":\"file1\",\"filename\":\"file1.jpg\",\"content\":\"[BASE64 encoded content block here]\",\"disposition\":\"inline\",\"content_id\":\"ii_139db99fdb5c3704\",\"type\":\"jpg\"}],\"personalizations\":[{\"to\":[{\"email\":\"john.doe@example.com\",\"name\":\"John Doe\"}],\"cc\":[{\"email\":\"jane.doe@example.com\",\"name\":\"Jane Doe\"}],\"bcc\":[{\"email\":\"sam.doe@example.com\",\"name\":\"Sam Doe\"}],\"custom_args\":{\"New Argument 1\":\"New Value 1\",\"activationAttempt\":\"1\",\"customerAccountNumber\":\"[CUSTOMER ACCOUNT NUMBER GOES HERE]\"},\"headers\":{\"X-Accept-Language\":\"en\",\"X-Mailer\":\"MyApp\"},\"send_at\":1409348513,\"substitutions\":{\"type\":\"object\",\"id\":\"substitutions\"},\"subject\":\"Hello, World!\"}],\"subject\":\"Hello, World!\",\"ip_pool_name\":\"[YOUR POOL NAME GOES HERE]\",\"content\":[{\"type\":\"text/html\",\"value\":\"

Hello, world!

\"}],\"headers\":{},\"asm\":{\"groups_to_display\":[1,2,3],\"group_id\":1},\"batch_id\":\"[YOUR BATCH ID GOES HERE]\",\"tracking_settings\":{\"subscription_tracking\":{\"text\":\"If you would like to unsubscribe and stop receiveing these emails <% click here %>.\",\"enable\":true,\"html\":\"If you would like to unsubscribe and stop receiving these emails <% clickhere %>.\",\"substitution_tag\":\"<%click here%>\"},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"%opentrack\"},\"click_tracking\":{\"enable\":true,\"enable_text\":true},\"ganalytics\":{\"utm_campaign\":\"[NAME OF YOUR REFERRER SOURCE]\",\"enable\":true,\"utm_name\":\"[NAME OF YOUR CAMPAIGN]\",\"utm_term\":\"[IDENTIFY PAID KEYWORDS HERE]\",\"utm_content\":\"[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]\",\"utm_medium\":\"[NAME OF YOUR MARKETING MEDIUM e.g. email]\"}},\"mail_settings\":{\"footer\":{\"text\":\"Thanks,/n The SendGrid Team\",\"enable\":true,\"html\":\"

Thanks
The SendGrid Team

\"},\"spam_check\":{\"threshold\":3,\"post_to_url\":\"http://example.com/compliance\",\"enable\":true},\"bypass_list_management\":{\"enable\":true},\"sandbox_mode\":{\"enable\":false},\"bcc\":{\"enable\":true,\"email\":\"ben.doe@example.com\"}},\"reply_to\":{\"email\":\"sam.smith@example.com\",\"name\":\"Sam Smith\"},\"sections\":{\"section\":{\":sectionName2\":\"section 2 text\",\":sectionName1\":\"section 1 text\"}},\"template_id\":\"[YOUR TEMPLATE ID GOES HERE]\",\"categories\":[\"category1\",\"category2\"],\"send_at\":1409348513}"); + Response response = sg.api(request); + Assert.assertEquals(202, response.getStatusCode()); + } + + @Test + public void test_mail_settings_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_address_whitelist_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/address_whitelist"); + request.setBody("{\"list\":[\"email1@example.com\",\"example.com\"],\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_address_whitelist_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/address_whitelist"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_bcc_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bcc"); + request.setBody("{\"enabled\":false,\"email\":\"email@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_bcc_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bcc"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_bounce_purge_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/bounce_purge"); + request.setBody("{\"hard_bounces\":5,\"soft_bounces\":5,\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_bounce_purge_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/bounce_purge"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_footer_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/footer"); + request.setBody("{\"html_content\":\"...\",\"enabled\":true,\"plain_content\":\"...\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_footer_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/footer"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_forward_bounce_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_bounce"); + request.setBody("{\"enabled\":true,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_forward_bounce_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_bounce"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_forward_spam_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/forward_spam"); + request.setBody("{\"enabled\":false,\"email\":\"\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_forward_spam_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/forward_spam"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_plain_content_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/plain_content"); + request.setBody("{\"enabled\":false}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_plain_content_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/plain_content"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_spam_check_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/spam_check"); + request.setBody("{\"url\":\"url\",\"max_score\":5,\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_spam_check_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/spam_check"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_template_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("mail_settings/template"); + request.setBody("{\"html_content\":\"<% body %>\",\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mail_settings_template_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mail_settings/template"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_mailbox_providers_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("mailbox_providers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("mailbox_providers", "test_string"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_partner_settings_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_partner_settings_new_relic_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("partner_settings/new_relic"); + request.setBody("{\"enable_subuser_statistics\":true,\"enabled\":true,\"license_key\":\"\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_partner_settings_new_relic_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("partner_settings/new_relic"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_scopes_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("scopes"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_senders_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_senders_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_senders__sender_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("senders/{sender_id}"); + request.setBody("{\"city\":\"Denver\",\"from\":{\"email\":\"from@example.com\",\"name\":\"Example INC\"},\"zip\":\"80202\",\"country\":\"United States\",\"state\":\"Colorado\",\"address_2\":\"Apt. 456\",\"address\":\"123 Elm St.\",\"reply_to\":{\"email\":\"replyto@example.com\",\"name\":\"Example INC\"},\"nickname\":\"My Sender ID\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_senders__sender_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_senders__sender_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("senders/{sender_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_senders__sender_id__resend_verification_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("senders/{sender_id}/resend_verification"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers"); + request.setBody("{\"username\":\"John@example.com\",\"ips\":[\"1.1.1.1\",\"2.2.2.2\"],\"password\":\"johns_password\",\"email\":\"John@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_reputations_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/reputations"); + request.addQueryParam("usernames", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("subusers", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_stats_monthly_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/monthly"); + request.addQueryParam("subuser", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers_stats_sums_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/stats/sums"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("sort_by_direction", "asc"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("subusers/{subuser_name}"); + request.setBody("{\"disabled\":false}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__ips_put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/ips"); + request.setBody("[\"127.0.0.1\"]"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__monitor_put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":500,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__monitor_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("subusers/{subuser_name}/monitor"); + request.setBody("{\"frequency\":50000,\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__monitor_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__monitor_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("subusers/{subuser_name}/monitor"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_subusers__subuser_name__stats_monthly_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("subusers/{subuser_name}/stats/monthly"); + request.addQueryParam("date", "test_string"); + request.addQueryParam("sort_by_direction", "asc"); + request.addQueryParam("limit", "1"); + request.addQueryParam("sort_by_metric", "test_string"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_blocks_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_blocks_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_blocks__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_blocks__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/blocks/{email}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_bounces_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("end_time", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_bounces_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces"); + request.setBody("{\"emails\":[\"example@example.com\",\"example2@example.com\"],\"delete_all\":true}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_bounces__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/bounces/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_bounces__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/bounces/{email}"); + request.addQueryParam("email_address", "example@example.com"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_invalid_emails_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_invalid_emails_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_invalid_emails__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_invalid_emails__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/invalid_emails/{email}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_spam_reports__email__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_reports/{email}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_spam_reports__email__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_reports/{email}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_spam_reports_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/spam_reports"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_suppression_spam_reports_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("suppression/spam_reports"); + request.setBody("{\"emails\":[\"example1@example.com\",\"example2@example.com\"],\"delete_all\":false}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_suppression_unsubscribes_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("suppression/unsubscribes"); + request.addQueryParam("start_time", "1"); + request.addQueryParam("limit", "1"); + request.addQueryParam("end_time", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates"); + request.setBody("{\"name\":\"example_name\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_templates_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}"); + request.setBody("{\"name\":\"new_example_name\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__versions_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions"); + request.setBody("{\"name\":\"example_version_name\",\"html_content\":\"<%body%>\",\"plain_content\":\"<%body%>\",\"active\":1,\"template_id\":\"ddb96bbc-9b92-425e-8979-99464621b543\",\"subject\":\"<%subject%>\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__versions__version_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + request.setBody("{\"active\":1,\"html_content\":\"<%body%>\",\"subject\":\"<%subject%>\",\"name\":\"updated_example_name\",\"plain_content\":\"<%body%>\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__versions__version_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__versions__version_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("templates/{template_id}/versions/{version_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_templates__template_id__versions__version_id__activate_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("templates/{template_id}/versions/{version_id}/activate"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_click_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/click"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_click_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/click"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_google_analytics_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/google_analytics"); + request.setBody("{\"utm_campaign\":\"website\",\"utm_term\":\"\",\"utm_content\":\"\",\"enabled\":true,\"utm_source\":\"sendgrid.com\",\"utm_medium\":\"email\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_google_analytics_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/google_analytics"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_open_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/open"); + request.setBody("{\"enabled\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_open_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/open"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_subscription_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("tracking_settings/subscription"); + request.setBody("{\"url\":\"url\",\"html_content\":\"html content\",\"enabled\":true,\"landing\":\"landing page html\",\"replace\":\"replacement tag\",\"plain_content\":\"text content\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_tracking_settings_subscription_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("tracking_settings/subscription"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_account_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/account"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_credits_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/credits"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_email_put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/email"); + request.setBody("{\"email\":\"example@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_email_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/email"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_password_put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/password"); + request.setBody("{\"new_password\":\"new_password\",\"old_password\":\"old_password\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_profile_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/profile"); + request.setBody("{\"city\":\"Orange\",\"first_name\":\"Example\",\"last_name\":\"User\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_profile_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/profile"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_scheduled_sends_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/scheduled_sends"); + request.setBody("{\"batch_id\":\"YOUR_BATCH_ID\",\"status\":\"pause\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_user_scheduled_sends_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_scheduled_sends__batch_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + request.setBody("{\"status\":\"pause\"}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_user_scheduled_sends__batch_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_scheduled_sends__batch_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/scheduled_sends/{batch_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_user_settings_enforced_tls_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/settings/enforced_tls"); + request.setBody("{\"require_tls\":true,\"require_valid_cert\":false}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_settings_enforced_tls_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/settings/enforced_tls"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_username_put() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PUT); + request.setEndpoint("user/username"); + request.setBody("{\"username\":\"test_username\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_username_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/username"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_event_settings_patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/event/settings"); + request.setBody("{\"group_resubscribe\":true,\"delivered\":true,\"group_unsubscribe\":true,\"spam_report\":true,\"url\":\"url\",\"enabled\":true,\"bounce\":true,\"deferred\":true,\"unsubscribe\":true,\"dropped\":true,\"open\":true,\"click\":true,\"processed\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_event_settings_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/event/settings"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_event_test_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/event/test"); + request.setBody("{\"url\":\"url\"}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_settings_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("user/webhooks/parse/settings"); + request.setBody("{\"url\":\"http://email.myhosthame.com\",\"send_raw\":false,\"hostname\":\"myhostname.com\",\"spam_check\":true}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_settings_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_settings__hostname__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + request.setBody("{\"url\":\"http://newdomain.com/parse\",\"send_raw\":true,\"spam_check\":false}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_settings__hostname__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_settings__hostname__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("user/webhooks/parse/settings/{hostname}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_user_webhooks_parse_stats_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("user/webhooks/parse/stats"); + request.addQueryParam("aggregated_by", "day"); + request.addQueryParam("limit", "test_string"); + request.addQueryParam("start_date", "2016-01-01"); + request.addQueryParam("end_date", "2016-04-01"); + request.addQueryParam("offset", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains"); + request.setBody("{\"automatic_security\":false,\"username\":\"john@example.com\",\"domain\":\"example.com\",\"default\":true,\"custom_spf\":true,\"ips\":[\"192.168.1.1\",\"192.168.1.2\"],\"subdomain\":\"news\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains"); + request.addQueryParam("username", "test_string"); + request.addQueryParam("domain", "test_string"); + request.addQueryParam("exclude_subusers", "true"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains_default_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/default"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains_subuser_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains_subuser_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/subuser"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__domain_id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/domains/{domain_id}"); + request.setBody("{\"default\":false,\"custom_spf\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__domain_id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__domain_id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{domain_id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__domain_id__subuser_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{domain_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__id__ips_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/ips"); + request.setBody("{\"ip\":\"192.168.0.1\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__id__ips__ip__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/domains/{id}/ips/{ip}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_domains__id__validate_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/domains/{id}/validate"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_ips_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips"); + request.setBody("{\"ip\":\"192.168.1.1\",\"domain\":\"example.com\",\"subdomain\":\"email\"}"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_whitelabel_ips_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips"); + request.addQueryParam("ip", "test_string"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_ips__id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_ips__id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/ips/{id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_whitelabel_ips__id__validate_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/ips/{id}/validate"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "201"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links"); + request.setBody("{\"default\":true,\"domain\":\"example.com\",\"subdomain\":\"mail\"}"); + request.addQueryParam("limit", "1"); + request.addQueryParam("offset", "1"); + Response response = sg.api(request); + Assert.assertEquals(201, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links"); + request.addQueryParam("limit", "1"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links_default_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/default"); + request.addQueryParam("domain", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links_subuser_get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links_subuser_delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/subuser"); + request.addQueryParam("username", "test_string"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links__id__patch() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.PATCH); + request.setEndpoint("whitelabel/links/{id}"); + request.setBody("{\"default\":true}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links__id__get() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.GET); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links__id__delete() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "204"); + + Request request = new Request(); + request.setMethod(Method.DELETE); + request.setEndpoint("whitelabel/links/{id}"); + Response response = sg.api(request); + Assert.assertEquals(204, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links__id__validate_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{id}/validate"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_whitelabel_links__link_id__subuser_post() throws IOException { + SendGrid sg = new SendGrid("SENDGRID_API_KEY"); + sg.addRequestHeader("X-Mock", "200"); + + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("whitelabel/links/{link_id}/subuser"); + request.setBody("{\"username\":\"jane@example.com\"}"); + Response response = sg.api(request); + Assert.assertEquals(200, response.getStatusCode()); + } + + @Test + public void test_add_impersonate_subuser() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + + sg.addImpersonateSubuser("subusername"); + Assert.assertEquals(sg.getRequestHeaders().get("on-behalf-of"), "subusername"); + } + + @Test + public void test_remove_impersonate_subuser() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + + sg.addImpersonateSubuser("subusername"); + Assert.assertEquals(sg.getRequestHeaders().get("on-behalf-of"), "subusername"); + + sg.removeImpersonateSubuser(); + Assert.assertEquals(sg.getRequestHeaders().get("on-behalf-of"), null); + } + + @Test + public void test_get_impersonate_subuser() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + + sg.addImpersonateSubuser("subusername"); + Assert.assertEquals(sg.getImpersonateSubuser(), "subusername"); + + sg.removeImpersonateSubuser(); + Assert.assertEquals(sg.getImpersonateSubuser(), null); + } + + @Test + public void test_sendgrid_object_headers_are_used_in_request() throws IOException { + Client client = mock(Client.class); + SendGrid sg = new SendGrid(SENDGRID_API_KEY, client); + sg.addRequestHeader("set-on-sendgrid", "123"); + + Request request = new Request(); + + sg.api(request); + verify(client).api(argThat((Request req) -> req.getHeaders().containsKey("set-on-sendgrid"))); + } + + @Test + public void test_request_headers_are_used_in_request() throws IOException { + Client client = mock(Client.class); + SendGrid sg = new SendGrid(SENDGRID_API_KEY, client); + + Request request = new Request(); + request.addHeader("set-on-request", "456"); + + sg.api(request); + verify(client).api(argThat((Request req) -> req.getHeaders().containsKey("set-on-request"))); + } + + + @Test + public void test_sendgrid_object_and_request_headers_are_both_used_in_request() throws IOException { + Client client = mock(Client.class); + SendGrid sg = new SendGrid(SENDGRID_API_KEY, client); + sg.addRequestHeader("set-on-sendgrid", "123"); + + Request request = new Request(); + request.addHeader("set-on-request", "456"); + + sg.api(request); + verify(client).api(argThat((Request req) -> + req.getHeaders().containsKey("set-on-sendgrid") && req.getHeaders().containsKey("set-on-request"))); + } + + @Test + public void test_request_headers_override_sendgrid_object_headers() throws IOException { + Client client = mock(Client.class); + SendGrid sg = new SendGrid(SENDGRID_API_KEY, client); + sg.addRequestHeader("set-on-both", "123"); + + Request request = new Request(); + request.addHeader("set-on-both", "456"); + + sg.api(request); + verify(client).api(argThat((Request req) -> req.getHeaders().get("set-on-both").equals("456"))); + } + + @Test + public void testSetResidency_happy_path_eu() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setDataResidency("eu"); + Assert.assertEquals(sg.getHost(), "api.eu.sendgrid.com"); + } + @Test + public void testSetResidency_happy_path_global() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setDataResidency("global"); + Assert.assertEquals(sg.getHost(), "api.sendgrid.com"); + } + + + @Test + public void testSetResidency_override_host() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setHost("api.new.com"); + sg.setDataResidency("eu"); + Assert.assertEquals(sg.getHost(), "api.eu.sendgrid.com"); + } + + @Test + public void testsetResidency_override_data_residency() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setDataResidency("eu"); + sg.setHost("api.new.com"); + Assert.assertEquals(sg.getHost(), "api.new.com"); + } + + @Test (expected = IllegalArgumentException.class) + public void testsetResidency_incorrect_region() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setDataResidency("foo"); + } + @Test (expected = IllegalArgumentException.class) + public void testsetResidency_null_region(){ + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + sg.setDataResidency(""); + } + @Test + public void testsetResidency_default_region() { + SendGrid sg = new SendGrid(SENDGRID_API_KEY); + Assert.assertEquals(sg.getHost(), "api.sendgrid.com"); + } } diff --git a/src/test/java/com/sendgrid/TestRequiredFilesExist.java b/src/test/java/com/sendgrid/TestRequiredFilesExist.java new file mode 100644 index 00000000..7675c8a2 --- /dev/null +++ b/src/test/java/com/sendgrid/TestRequiredFilesExist.java @@ -0,0 +1,75 @@ +package com.sendgrid; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import org.junit.Test; + +public class TestRequiredFilesExist { + + // ./Dockerfile + @Test + public void checkDockerExists() { + assertTrue(new File("./Dockerfile").exists()); + } + + // ./.env_sample + @Test + public void checkEnvSampleExists() { + assertTrue(new File("./.env_sample").exists()); + } + + // ./.gitignore + @Test + public void checkGitIgnoreExists() { + assertTrue(new File("./.gitignore").exists()); + } + + // ./CHANGELOG.md + @Test + public void checkChangelogExists() { + assertTrue(new File("./CHANGELOG.md").exists()); + } + + // ./CODE_OF_CONDUCT.md + @Test + public void checkCodeOfConductExists() { + assertTrue(new File("./CODE_OF_CONDUCT.md").exists()); + } + + // ./CONTRIBUTING.md + @Test + public void checkContributingGuideExists() { + assertTrue(new File("./CONTRIBUTING.md").exists()); + } + + // ./LICENSE + @Test + public void checkLicenseExists() { + assertTrue(new File("./LICENSE").exists()); + } + + // ./PULL_REQUEST_TEMPLATE.md + @Test + public void checkPullRequestExists() { + assertTrue(new File("./PULL_REQUEST_TEMPLATE.md").exists()); + } + + // ./README.md + @Test + public void checkReadMeExists() { + assertTrue(new File("./README.md").exists()); + } + + // ./TROUBLESHOOTING.md + @Test + public void checkTroubleShootingGuideExists() { + assertTrue(new File("./TROUBLESHOOTING.md").exists()); + } + + // ./USAGE.md + @Test + public void checkUsageGuideExists() { + assertTrue(new File("./USAGE.md").exists()); + } +} diff --git a/src/test/java/com/sendgrid/TwilioEmailTest.java b/src/test/java/com/sendgrid/TwilioEmailTest.java new file mode 100644 index 00000000..e07c2ca5 --- /dev/null +++ b/src/test/java/com/sendgrid/TwilioEmailTest.java @@ -0,0 +1,29 @@ +package com.sendgrid; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class TwilioEmailTest { + + @Test + public void testInitialization() { + final TwilioEmail sg = new TwilioEmail("username", "password"); + Assert.assertEquals("email.twilio.com", sg.getHost()); + Assert.assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", sg.getRequestHeaders().get("Authorization")); + } + + @Test + public void testConstructWithClient() throws IOException { + final Client client = mock(Client.class); + final TwilioEmail sg = new TwilioEmail("username", "password", client); + final Request request = new Request(); + + sg.makeCall(request); + verify(client).api(request); + } +} diff --git a/src/test/java/com/sendgrid/helpers/AttachmentBuilderTest.java b/src/test/java/com/sendgrid/helpers/AttachmentBuilderTest.java new file mode 100644 index 00000000..adef08aa --- /dev/null +++ b/src/test/java/com/sendgrid/helpers/AttachmentBuilderTest.java @@ -0,0 +1,49 @@ +package com.sendgrid.helpers; + +import com.sendgrid.helpers.mail.objects.Attachments; +import org.apache.commons.codec.binary.Base64; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.Charset; + +public class AttachmentBuilderTest { + + @Test + public void testCreateAttachments() { + String fileName = "book.txt"; + String type = "text/plain"; + String content = "This test checks if the builder works fine"; + InputStream contentStream = new ByteArrayInputStream(content.getBytes(Charset.forName("UTF-8"))); + String contentId = "someId"; + String disposition = "someDisposition"; + + Attachments attachments = new Attachments.Builder(fileName, contentStream) + .withType(type) + .withContentId(contentId) + .withDisposition(disposition) + .build(); + + Assert.assertEquals(attachments.getType(), type); + Assert.assertEquals(attachments.getFilename(), fileName); + Assert.assertEquals(attachments.getContentId(), contentId); + Assert.assertEquals(attachments.getDisposition(), disposition); + Assert.assertEquals(attachments.getContent(), Base64.encodeBase64String(content.getBytes(Charset.forName("UTF-8")))); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateAttachmentsMissingRequiredFileNameParam() { + String content = "This test checks if the builder works fine"; + InputStream contentStream = new ByteArrayInputStream(content.getBytes(Charset.forName("UTF-8"))); + Attachments attachments = new Attachments.Builder(null, contentStream).build(); + } + + @Test(expected = IllegalArgumentException.class) + public void testCreateAttachmentsMissingRequiredContentParam() { + String type = "text"; + String content = null; + Attachments attachments = new Attachments.Builder(type, content).build(); + } +} diff --git a/src/test/java/com/sendgrid/helpers/MailTest.java b/src/test/java/com/sendgrid/helpers/MailTest.java new file mode 100644 index 00000000..22c7f8db --- /dev/null +++ b/src/test/java/com/sendgrid/helpers/MailTest.java @@ -0,0 +1,292 @@ +package com.sendgrid.helpers; + +import com.sendgrid.helpers.mail.Mail; +import com.sendgrid.helpers.mail.objects.*; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import java.io.IOException; + +public class MailTest { + + @Test + public void testHelloWorld() throws IOException { + Email from = new Email("test@example.com"); + String subject = "Sending with SendGrid is Fun"; + Email to = new Email("test@example.com"); + Content content = new Content("text/plain", "and easy to do anywhere, even with Java"); + Mail mail = new Mail(from, subject, to, content); + + Assert.assertEquals(mail.build(), "{\"from\":{\"email\":\"test@example.com\"},\"subject\":\"Sending with SendGrid is Fun\",\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"and easy to do anywhere, even with Java\"}]}"); + } + + @Test + public void testKitchenSink() throws IOException { + Mail mail = new Mail(); + + Email fromEmail = new Email(); + fromEmail.setName("Example User"); + fromEmail.setEmail("test@example.com"); + mail.setFrom(fromEmail); + + mail.setSubject("Hello World from the SendGrid Java Library"); + + Personalization personalization = new Personalization(); + Email to = new Email(); + to.setName("Example User"); + to.setEmail("test@example.com"); + personalization.addTo(to); + to.setName("Example User"); + to.setEmail("test@example.com"); + personalization.addTo(to); + Email cc = new Email(); + cc.setName("Example User"); + cc.setEmail("test@example.com"); + personalization.addCc(cc); + cc.setName("Example User"); + cc.setEmail("test@example.com"); + personalization.addCc(cc); + Email bcc = new Email(); + bcc.setName("Example User"); + bcc.setEmail("test@example.com"); + personalization.addBcc(bcc); + bcc.setName("Example User"); + bcc.setEmail("test@example.com"); + personalization.addBcc(bcc); + personalization.setSubject("Hello World from the Personalized SendGrid Java Library"); + personalization.addHeader("X-Test", "test"); + personalization.addHeader("X-Mock", "true"); + personalization.addSubstitution("%name%", "Example User"); + personalization.addSubstitution("%city%", "Denver"); + personalization.addCustomArg("user_id", "343"); + personalization.addCustomArg("type", "marketing"); + personalization.setSendAt(1443636843); + mail.addPersonalization(personalization); + + Personalization personalization2 = new Personalization(); + Email to2 = new Email(); + to2.setName("Example User"); + to2.setEmail("test@example.com"); + personalization2.addTo(to2); + to2.setName("Example User"); + to2.setEmail("test@example.com"); + personalization2.addTo(to2); + Email fromEmail2 = new Email(); + fromEmail2.setName("Example Sender"); + fromEmail2.setEmail("sender@example.com"); + personalization2.setFrom(fromEmail2); + Email cc2 = new Email(); + cc2.setName("Example User"); + cc2.setEmail("test@example.com"); + personalization2.addCc(cc2); + cc2.setName("Example User"); + cc2.setEmail("test@example.com"); + personalization2.addCc(cc2); + Email bcc2 = new Email(); + bcc2.setName("Example User"); + bcc2.setEmail("test@example.com"); + personalization2.addBcc(bcc2); + bcc2.setName("Example User"); + bcc2.setEmail("test@example.com"); + personalization2.addBcc(bcc2); + personalization2.setSubject("Hello World from the Personalized SendGrid Java Library"); + personalization2.addHeader("X-Test", "test"); + personalization2.addHeader("X-Mock", "true"); + personalization2.addSubstitution("%name%", "Example User"); + personalization2.addSubstitution("%city%", "Denver"); + personalization2.addCustomArg("user_id", "343"); + personalization2.addCustomArg("type", "marketing"); + personalization2.setSendAt(1443636843); + mail.addPersonalization(personalization2); + + Personalization personalization3 = new Personalization(); + Email to3 = new Email(); + to3.setName("Example User"); + to3.setEmail("test@example.com"); + personalization3.addTo(to3); + to3.setName("Example User"); + to3.setEmail("test@example.com"); + personalization3.addTo(to3); + Email fromEmail3 = new Email(); + fromEmail3.setName("Example Sender2"); + fromEmail3.setEmail("sender2@example.com"); + personalization3.setFrom(fromEmail3); + Email cc3 = new Email(); + cc3.setName("Example User"); + cc3.setEmail("test@example.com"); + personalization3.addCc(cc3); + cc3.setName("Example User"); + cc3.setEmail("test@example.com"); + personalization3.addCc(cc3); + Email bcc3 = new Email(); + bcc3.setName("Example User"); + bcc3.setEmail("test@example.com"); + personalization3.addBcc(bcc3); + bcc3.setName("Example User"); + bcc3.setEmail("test@example.com"); + personalization3.addBcc(bcc3); + personalization3.setSubject("Hello World from the Personalized SendGrid Java Library"); + personalization3.addHeader("X-Test", "test"); + personalization3.addHeader("X-Mock", "true"); + List> items = new ArrayList<>(); + Map item1 = new HashMap<>(); + item1.put("text", "New Line Sneakers"); + item1.put("price", "$ 79.95"); + items.add(item1); + Map item2 = new HashMap<>(); + item2.put("text", "Old Line Sneakers"); + item1.put("price", "$ 59.95"); + items.add(item2); + personalization3.addDynamicTemplateData("name", "Example User"); + personalization3.addDynamicTemplateData("city", "Denver"); + personalization3.addDynamicTemplateData("items", items); + personalization3.addCustomArg("user_id", "343"); + personalization3.addCustomArg("type", "marketing"); + personalization3.setSendAt(1443636843); + mail.addPersonalization(personalization3); + + Content content = new Content(); + content.setType("text/plain"); + content.setValue("some text here"); + mail.addContent(content); + content.setType("text/html"); + content.setValue("some text here"); + mail.addContent(content); + + Attachments attachments = new Attachments(); + attachments.setContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"); + attachments.setType("application/pdf"); + attachments.setFilename("balance_001.pdf"); + attachments.setDisposition("attachment"); + attachments.setContentId("Balance Sheet"); + mail.addAttachments(attachments); + + Attachments attachments2 = new Attachments(); + attachments2.setContent("BwdW"); + attachments2.setType("image/png"); + attachments2.setFilename("banner.png"); + attachments2.setDisposition("inline"); + attachments2.setContentId("Banner"); + mail.addAttachments(attachments2); + + mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + + mail.addSection("%section1%", "Substitution Text for Section 1"); + mail.addSection("%section2%", "Substitution Text for Section 2"); + + mail.addHeader("X-Test1", "1"); + mail.addHeader("X-Test2", "2"); + + mail.addCategory("May"); + mail.addCategory("2016"); + + mail.addCustomArg("campaign", "welcome"); + mail.addCustomArg("weekday", "morning"); + + mail.setSendAt(1443636842); + + ASM asm = new ASM(); + asm.setGroupId(99); + asm.setGroupsToDisplay(new int[] {4,5,6,7,8}); + mail.setASM(asm); + + // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) to work + // mail.setBatchId("sendgrid_batch_id"); + + mail.setIpPoolId("23"); + + MailSettings mailSettings = new MailSettings(); + BccSettings bccSettings = new BccSettings(); + bccSettings.setEnable(true); + bccSettings.setEmail("test@example.com"); + mailSettings.setBccSettings(bccSettings); + Setting sandBoxMode = new Setting(); + sandBoxMode.setEnable(true); + mailSettings.setSandboxMode(sandBoxMode); + Setting bypassListManagement = new Setting(); + bypassListManagement.setEnable(true); + Setting bypassSpamManagement = new Setting(); + bypassSpamManagement.setEnable(true); + Setting bypassBounceManagement = new Setting(); + bypassBounceManagement.setEnable(true); + Setting bypassUnsubscribeManagement = new Setting(); + bypassUnsubscribeManagement.setEnable(true); + mailSettings.setBypassListManagement(bypassListManagement); + mailSettings.setBypassSpamManagement(bypassSpamManagement); + mailSettings.setBypassBounceManagement(bypassBounceManagement); + mailSettings.setBypassUnsubscribeManagement(bypassUnsubscribeManagement); + FooterSetting footerSetting = new FooterSetting(); + footerSetting.setEnable(true); + footerSetting.setText("Footer Text"); + footerSetting.setHtml("Footer Text"); + mailSettings.setFooterSetting(footerSetting); + SpamCheckSetting spamCheckSetting = new SpamCheckSetting(); + spamCheckSetting.setEnable(true); + spamCheckSetting.setSpamThreshold(1); + spamCheckSetting.setPostToUrl("https://spamcatcher.sendgrid.com"); + mailSettings.setSpamCheckSetting(spamCheckSetting); + mail.setMailSettings(mailSettings); + + TrackingSettings trackingSettings = new TrackingSettings(); + ClickTrackingSetting clickTrackingSetting = new ClickTrackingSetting(); + clickTrackingSetting.setEnable(true); + clickTrackingSetting.setEnableText(false); + trackingSettings.setClickTrackingSetting(clickTrackingSetting); + OpenTrackingSetting openTrackingSetting = new OpenTrackingSetting(); + openTrackingSetting.setEnable(true); + openTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + trackingSettings.setOpenTrackingSetting(openTrackingSetting); + SubscriptionTrackingSetting subscriptionTrackingSetting = new SubscriptionTrackingSetting(); + subscriptionTrackingSetting.setEnable(true); + subscriptionTrackingSetting.setText("text to insert into the text/plain portion of the message"); + subscriptionTrackingSetting.setHtml("html to insert into the text/html portion of the message"); + subscriptionTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); + trackingSettings.setSubscriptionTrackingSetting(subscriptionTrackingSetting); + GoogleAnalyticsSetting googleAnalyticsSetting = new GoogleAnalyticsSetting(); + googleAnalyticsSetting.setEnable(true); + googleAnalyticsSetting.setCampaignSource("some source"); + googleAnalyticsSetting.setCampaignTerm("some term"); + googleAnalyticsSetting.setCampaignContent("some content"); + googleAnalyticsSetting.setCampaignName("some name"); + googleAnalyticsSetting.setCampaignMedium("some medium"); + trackingSettings.setGoogleAnalyticsSetting(googleAnalyticsSetting); + mail.setTrackingSettings(trackingSettings); + + Email replyTo = new Email(); + replyTo.setName("Example User"); + replyTo.setEmail("test@example.com"); + mail.setReplyTo(replyTo); + + Assert.assertEquals(mail.build(), "{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Hello World from the SendGrid Java Library\",\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"substitutions\":{\"%city%\":\"Denver\",\"%name%\":\"Example User\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"send_at\":1443636843},{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"from\":{\"name\":\"Example Sender\",\"email\":\"sender@example.com\"},\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"substitutions\":{\"%city%\":\"Denver\",\"%name%\":\"Example User\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"send_at\":1443636843},{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"from\":{\"name\":\"Example Sender2\",\"email\":\"sender2@example.com\"},\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"dynamic_template_data\":{\"city\":\"Denver\",\"items\":[{\"price\":\"$ 59.95\",\"text\":\"New Line Sneakers\"},{\"text\":\"Old Line Sneakers\"}],\"name\":\"Example User\"},\"send_at\":1443636843}],\"content\":[{\"type\":\"text/plain\",\"value\":\"some text here\"},{\"type\":\"text/html\",\"value\":\"some text here\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"BwdW\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"sections\":{\"%section1%\":\"Substitution Text for Section 1\",\"%section2%\":\"Substitution Text for Section 2\"},\"headers\":{\"X-Test1\":\"1\",\"X-Test2\":\"2\"},\"categories\":[\"May\",\"2016\"],\"custom_args\":{\"campaign\":\"welcome\",\"weekday\":\"morning\"},\"send_at\":1443636842,\"asm\":{\"group_id\":99,\"groups_to_display\":[4,5,6,7,8]},\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test@example.com\"},\"bypass_list_management\":{\"enable\":true},\"bypass_spam_management\":{\"enable\":true},\"bypass_bounce_management\":{\"enable\":true},\"bypass_unsubscribe_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Footer Text\",\"html\":\"Footer Text\"},\"sandbox_mode\":{\"enable\":true},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://spamcatcher.sendgrid.com\"}},\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":false},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"html to insert into the text/html portion of the message\",\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_campaign\":\"some name\",\"utm_medium\":\"some medium\"}},\"reply_to\":{\"name\":\"Example User\",\"email\":\"test@example.com\"}}"); + } + + @Test + public void fromShouldReturnCorrectFrom() { + Mail mail = new Mail(); + Email from = new Email(); + mail.setFrom(from); + + Assert.assertSame(from, mail.getFrom()); + } + + @Test + public void mailDeserialization() throws IOException { + Email to = new Email("foo@bar.com"); + Content content = new Content("text/plain", "test"); + Email from = new Email("no-reply@bar.com"); + Mail mail = new Mail(from, "subject", to, content); + + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(mail); + Mail deserialized = mapper.readValue(json, Mail.class); + + Assert.assertEquals(deserialized, mail); + } +} diff --git a/src/test/java/com/sendgrid/helpers/eventwebhook/EventWebhookTest.java b/src/test/java/com/sendgrid/helpers/eventwebhook/EventWebhookTest.java new file mode 100644 index 00000000..d73cedbc --- /dev/null +++ b/src/test/java/com/sendgrid/helpers/eventwebhook/EventWebhookTest.java @@ -0,0 +1,124 @@ +package com.sendgrid.helpers.eventwebhook; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.security.Security; +import java.security.interfaces.ECPublicKey; +import java.util.Collections; +import java.util.List; + +public class EventWebhookTest { + private static class Event { + public Event(final String email, + final String event, + final String reason, + final String sgEventId, + final String sgMessageId, + final String smtpId, + final long timestamp) { + this.email = email; + this.event = event; + this.reason = reason; + this.sgEventId = sgEventId; + this.sgMessageId = sgMessageId; + this.smtpId = smtpId; + this.timestamp = timestamp; + } + + public String email; + public String event; + public String reason; + @JsonProperty("sg_event_id") + public String sgEventId; + @JsonProperty("sg_message_id") + public String sgMessageId; + @JsonProperty("smtp-id") + public String smtpId; + @JsonProperty("timestamp") + public long timestamp; + } + + private static final String PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE83T4O/n84iotIvIW4mdBgQ/7dAfSmpqIM8kF9mN1flpVKS3GRqe62gw+2fNNRaINXvVpiglSI8eNEc6wEA3F+g=="; + private static final String SIGNATURE = "MEUCIGHQVtGj+Y3LkG9fLcxf3qfI10QysgDWmMOVmxG0u6ZUAiEAyBiXDWzM+uOe5W0JuG+luQAbPIqHh89M15TluLtEZtM="; + private static final String TIMESTAMP = "1600112502"; + private static final List EVENTS = Collections.singletonList(new Event( + "hello@world.com", + "dropped", + "Bounced Address", + "ZHJvcC0xMDk5NDkxOS1MUnpYbF9OSFN0T0doUTRrb2ZTbV9BLTA", + "LRzXl_NHStOGhQ4kofSm_A.filterdrecv-p3mdw1-756b745b58-kmzbl-18-5F5FC76C-9.0", + "", + 1600112492)); + + private static String PAYLOAD; + + @BeforeClass + public static void setUp() throws JsonProcessingException { + Security.addProvider(new BouncyCastleProvider()); + + // Be sure to include the trailing carriage return and newline! + PAYLOAD = new ObjectMapper().writeValueAsString(EVENTS) + "\r\n"; + } + + @Test + public void testVerifySignature() throws Exception { + Assert.assertTrue(verify( + PUBLIC_KEY, + PAYLOAD, + SIGNATURE, + TIMESTAMP + )); + } + + @Test + public void testBadKey() throws Exception { + Assert.assertFalse(verify( + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqTxd43gyp8IOEto2LdIfjRQrIbsd4SXZkLW6jDutdhXSJCWHw8REntlo7aNDthvj+y7GjUuFDb/R1NGe1OPzpA==", + PAYLOAD, + SIGNATURE, + TIMESTAMP + )); + } + + @Test + public void testBadPayload() throws Exception { + Assert.assertFalse(verify( + PUBLIC_KEY, + "payload", + SIGNATURE, + TIMESTAMP + )); + } + + @Test + public void testBadSignature() throws Exception { + Assert.assertFalse(verify( + PUBLIC_KEY, + PAYLOAD, + "MEUCIQCtIHJeH93Y+qpYeWrySphQgpNGNr/U+UyUlBkU6n7RAwIgJTz2C+8a8xonZGi6BpSzoQsbVRamr2nlxFDWYNH3j/0=", + TIMESTAMP + )); + } + + @Test + public void testBadTimestamp() throws Exception { + Assert.assertFalse(verify( + PUBLIC_KEY, + PAYLOAD, + SIGNATURE, + "timestamp" + )); + } + + private boolean verify(final String publicKey, final String payload, final String signature, final String timestamp) throws Exception { + final EventWebhook ew = new EventWebhook(); + final ECPublicKey ellipticCurvePublicKey = ew.ConvertPublicKeyToECDSA(publicKey); + return ew.VerifySignature(ellipticCurvePublicKey, payload, signature, timestamp); + } +} diff --git a/src/test/java/com/sendgrid/helpers/mail/objects/SettingsSerializationTest.java b/src/test/java/com/sendgrid/helpers/mail/objects/SettingsSerializationTest.java new file mode 100644 index 00000000..2f7d47c2 --- /dev/null +++ b/src/test/java/com/sendgrid/helpers/mail/objects/SettingsSerializationTest.java @@ -0,0 +1,95 @@ +package com.sendgrid.helpers.mail.objects; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sendgrid.helpers.mail.objects.BccSettings; +import com.sendgrid.helpers.mail.objects.ClickTrackingSetting; +import com.sendgrid.helpers.mail.objects.FooterSetting; +import com.sendgrid.helpers.mail.objects.GoogleAnalyticsSetting; +import com.sendgrid.helpers.mail.objects.OpenTrackingSetting; +import com.sendgrid.helpers.mail.objects.SpamCheckSetting; +import com.sendgrid.helpers.mail.objects.SubscriptionTrackingSetting; +import org.junit.Assert; +import org.junit.Test; + +public class SettingsSerializationTest { + + private ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testSettingSerialization() throws Exception { + Setting setting = new Setting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + Assert.assertEquals(json, "{\"enable\":false}"); + } + + @Test + public void testOpenTrackingSettingSerialization() throws Exception { + OpenTrackingSetting setting = new OpenTrackingSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + Assert.assertEquals(json, "{\"enable\":false}"); + } + + @Test + public void testClickTrackingSettingSerialization() throws Exception { + ClickTrackingSetting setting = new ClickTrackingSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false,\"enable_text\":false}"); + } + + @Test + public void testSubscriptionTrackingSettingSerialization() throws Exception { + SubscriptionTrackingSetting setting = new SubscriptionTrackingSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false}"); + } + + @Test + public void testGoogleAnalyticsTrackingSettingSerialization() throws Exception { + GoogleAnalyticsSetting setting = new GoogleAnalyticsSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false}"); + } + + @Test + public void testSpamCheckSettingSerialization() throws Exception { + SpamCheckSetting setting = new SpamCheckSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false,\"threshold\":0}"); + } + + @Test + public void testFooterSettingSerialization() throws Exception { + FooterSetting setting = new FooterSetting(); + setting.setEnable(false); + + String json = mapper.writeValueAsString(setting); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false}"); + } + + @Test + public void testBccSettingsSerialization() throws Exception { + BccSettings settings = new BccSettings(); + settings.setEnable(false); + + String json = mapper.writeValueAsString(settings); + System.out.println(json); + Assert.assertEquals(json, "{\"enable\":false}"); + } +} diff --git a/src/test/resources/image.png b/src/test/resources/image.png deleted file mode 100644 index d53325e4..00000000 Binary files a/src/test/resources/image.png and /dev/null differ diff --git a/src/test/resources/test.txt b/src/test/resources/test.txt deleted file mode 100644 index 6de7b8c6..00000000 --- a/src/test/resources/test.txt +++ /dev/null @@ -1 +0,0 @@ -This is a test file. diff --git a/static/img/github-fork.png b/static/img/github-fork.png new file mode 100644 index 00000000..6503be36 Binary files /dev/null and b/static/img/github-fork.png differ diff --git a/static/img/github-sign-up.png b/static/img/github-sign-up.png new file mode 100644 index 00000000..491392b8 Binary files /dev/null and b/static/img/github-sign-up.png differ diff --git a/twilio_sendgrid_logo.png b/twilio_sendgrid_logo.png new file mode 100644 index 00000000..a4c22239 Binary files /dev/null and b/twilio_sendgrid_logo.png differ diff --git a/use-cases/README.md b/use-cases/README.md new file mode 100644 index 00000000..204d8609 --- /dev/null +++ b/use-cases/README.md @@ -0,0 +1,17 @@ +This directory provides examples for specific use cases. + +Please [open an issue](https://github.com/sendgrid/sendgrid-ruby/issues) or [make a pull request](https://github.com/sendgrid/sendgrid-ruby/pulls) for any use cases you would like us to document here. Thank you! + +# Email Use Cases +* [Transactional Templates](transactional-templates.md) +* [Legacy Templates](legacy-templates.md) +* [Personalizations](personalizations.md) + +# Twilio Use Cases +* [Twilio Setup](twilio-setup.md) +* [Send an Email With Twilio Email (Pilot)](twilio-email.md) +* [Send an SMS Message](sms.md) + +# Non-Email Use Cases +* [How to Set up a Domain Authentication](domain-authentication.md) +* [How to View Email Statistics](email-statistics.md) diff --git a/use-cases/domain-authentication.md b/use-cases/domain-authentication.md new file mode 100644 index 00000000..5bc6a750 --- /dev/null +++ b/use-cases/domain-authentication.md @@ -0,0 +1,11 @@ +# How to Setup a Domain Authentication + +You can find documentation for how to set up a domain authentication via the UI [here](https://sendgrid.com/docs/ui/account-and-settings/how-to-set-up-domain-authentication/) and via API [here](USAGE.md#sender-authentication). + +Find more information about all of Twilio SendGrid's authentication related documentation [here](https://sendgrid.com/docs/ui/account-and-settings/). + +# How to View Email Statistics + +You can find documentation for how to view your email statistics via the UI [here](https://app.sendgrid.com/statistics) and via API [here](USAGE.md#stats). + +Alternatively, we can post events to a URL of your choice via our [Event Webhook](https://sendgrid.com/docs/API_Reference/Webhooks/event.html) about events that occur as Twilio SendGrid processes your email. diff --git a/use-cases/email-statistics.md b/use-cases/email-statistics.md new file mode 100644 index 00000000..ace54b6a --- /dev/null +++ b/use-cases/email-statistics.md @@ -0,0 +1,5 @@ +# How to View Email Statistics + +You can find documentation for how to view your email statistics via the UI [here](https://app.sendgrid.com/statistics) and via API [here](USAGE.md#stats). + +Alternatively, we can post events to a URL of your choice via our [Event Webhook](https://sendgrid.com/docs/API_Reference/Webhooks/event.html) about events that occur as Twilio SendGrid processes your email. diff --git a/use-cases/legacy-templates.md b/use-cases/legacy-templates.md new file mode 100644 index 00000000..70239088 --- /dev/null +++ b/use-cases/legacy-templates.md @@ -0,0 +1,104 @@ +# Legacy Templates + +For this example, we assume you have created a [legacy transactional template](https://sendgrid.com/docs/User_Guide/Transactional_Templates/index.html) in the UI or via the API. Following is the template content we used for testing. + +Template ID (replace with your own): + +```text +13b8f94f-bcae-4ec6-b752-70d6cb59f932 +``` + +Email Subject: + +```text +<%subject%> +``` + +Template Body: + +```html + + + + + + Hello -name-, +

+ I'm glad you are trying out the template feature! +

+ <%body%> +

+ I hope you are having a great day in -city- :) +

+ + +``` + +## With Mail Helper Class + +```java +import com.sendgrid.*; +import java.io.IOException; +public class Example { + public static void main(String[] args) throws IOException { + Email from = new Email("test@example.com"); + String subject = "I'm replacing the subject tag"; + Email to = new Email("test@example.com"); + Content content = new Content("text/html", "I'm replacing the body tag"); + Mail mail = new Mail(from, subject, to, content); + mail.personalization.get(0).addSubstitution("-name-", "Example User"); + mail.personalization.get(0).addSubstitution("-city-", "Denver"); + mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + try { + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} +``` + +## Without Mail Helper Class + +```java +import com.sendgrid.*; +import java.io.IOException; +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{ + \"personalizations\": + [{ + \"to\": [{\"email\": \"test@example.com\"}], + \"substitutions\": {\"-name-\": \"Example User\", \"-city-\": \"Denver\"}, + \"subject\": \"Hello World from the Twilio SendGrid Java Library!\" + }], + \"from\": {\"email\": \"test@example.com\"}, + \"content\": + [{ + \"type\": \"text/html\", + \"value\": \"I'm replacing the body tag\" + }] + ,\"template_id\": \"13b8f94f-bcae-4ec6-b752-70d6cb59f932\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} +``` diff --git a/use-cases/personalizations.md b/use-cases/personalizations.md new file mode 100644 index 00000000..494161d8 --- /dev/null +++ b/use-cases/personalizations.md @@ -0,0 +1,48 @@ +# Personalizations + +This example goes over how to send multiple emails using personalizations with the helper class. + +A similar example can be found in `examples/helpers/mail/MultipleEmailsMultipleRecipients.java`, and further documentation can be found [here](https://docs.sendgrid.com/for-developers/sending-email/personalizations). + +```java +import com.sendgrid.*; +import java.io.IOException; + +public class Example { + public static void main(String[] args) { + final Mail mail = new Mail(); + + // Note that the domain of the from addresses should be the same + mail.setFrom(new Email("test@example.com", "Example User")); + mail.setSubject("I'm the original subject"); + mail.addContent(new Content("text/plain", "and this is some content")); + mail.addContent(new Content("text/html", "and this is some content")); + + final Personalization personalization1 = new Personalization(); + personalization1.addTo(new Email("test1@example.com", "Example User1")); + personalization1.addCc(new Email("test2@example.com", "Example User2")); + mail.addPersonalization(personalization1); + + final Personalization personalization2 = new Personalization(); + personalization2.addTo(new Email("test3@example.com", "Example User3")); + personalization2.setFrom(new Email("test4@example.com", "Example User4")); + personalization2.setSubject(new Subject("I'm the personalized subject")); + personalization2.addBcc(new Email("test5@example.com", "Example User5")); + mail.addPersonalization(personalization2); + + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + try { + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} +``` \ No newline at end of file diff --git a/use-cases/sms.md b/use-cases/sms.md new file mode 100644 index 00000000..3dfe4cfa --- /dev/null +++ b/use-cases/sms.md @@ -0,0 +1,19 @@ +First, follow the [Twilio Setup](twilio-setup.md) guide for creating a Twilio account and setting up environment variables with the proper credentials. + +Then, install the Twilio Helper Library by following the [installation steps](https://github.com/twilio/twilio-java#installation). + +Finally, send a message. + +```java +String accountSid = System.getenv("TWILIO_ACCOUNT_SID"); +String authToken = System.getenv("TWILIO_AUTH_TOKEN"); +Twilio.init(accountSid, authToken); +Message message = Message.creator( + new PhoneNumber("+15558881234"), // To number + new PhoneNumber("+15559994321"), // From number + "Hello world!" // SMS body +).create(); +System.out.println(message.getSid()); +``` + +For more information, please visit the [Twilio SMS Java documentation](https://www.twilio.com/docs/sms/quickstart/java). diff --git a/use-cases/transactional-templates.md b/use-cases/transactional-templates.md new file mode 100644 index 00000000..ba2b39e2 --- /dev/null +++ b/use-cases/transactional-templates.md @@ -0,0 +1,107 @@ +# Transactional Templates + +For this example, we assume you have created a [transactional template](https://docs.sendgrid.com/ui/sending-email/create-and-edit-legacy-transactional-templates). Following is the template content we used for testing. + +Template ID (replace with your own): + +```text +13b8f94f-bcae-4ec6-b752-70d6cb59f932 +``` + +Email Subject: + +```text +<%subject%> +``` + +Template Body: + +```html + + + + + + Hello -name-, +

+ I'm glad you are trying out the template feature! +

+ <%body%> +

+ I hope you are having a great day in -city- :) +

+ + +``` + +## With Mail Helper Class + +```java +import com.sendgrid.*; +import java.io.IOException; + +public class Example { + public static void main(String[] args) throws IOException { + Email from = new Email("test@example.com"); + String subject = "I'm replacing the subject tag"; + Email to = new Email("test@example.com"); + Content content = new Content("text/html", "I'm replacing the body tag"); + Mail mail = new Mail(from, subject, to, content); + mail.personalization.get(0).addSubstitution("-name-", "Example User"); + mail.personalization.get(0).addSubstitution("-city-", "Denver"); + mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + try { + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody(mail.build()); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} +``` + +## Without Mail Helper Class + +```java +import com.sendgrid.*; +import java.io.IOException; + +public class Example { + public static void main(String[] args) throws IOException { + try { + SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY")); + Request request = new Request(); + request.setMethod(Method.POST); + request.setEndpoint("mail/send"); + request.setBody("{ + \"personalizations\": + [{ + \"to\": [{\"email\": \"test@example.com\"}], + \"substitutions\": {\"-name-\": \"Example User\", \"-city-\": \"Denver\"}, + \"subject\": \"Hello World from the Twilio SendGrid Java Library!\" + }], + \"from\": {\"email\": \"test@example.com\"}, + \"content\": + [{ + \"type\": \"text/html\", + \"value\": \"I'm replacing the body tag\" + }] + ,\"template_id\": \"13b8f94f-bcae-4ec6-b752-70d6cb59f932\"}"); + Response response = sg.api(request); + System.out.println(response.getStatusCode()); + System.out.println(response.getBody()); + System.out.println(response.getHeaders()); + } catch (IOException ex) { + throw ex; + } + } +} +``` diff --git a/use-cases/twilio-email.md b/use-cases/twilio-email.md new file mode 100644 index 00000000..a0227a0f --- /dev/null +++ b/use-cases/twilio-email.md @@ -0,0 +1,11 @@ +First, follow the [Twilio Setup](twilio-setup.md) guide for creating a Twilio account and setting up environment variables with the proper credentials. + +Then, initialize the Twilio Email Client. + +```java +TwilioEmail mailClient = new TwilioEmail(System.getenv("TWILIO_API_KEY"), System.getenv("TWILIO_API_SECRET")); +// or +TwilioEmail mailClient = new TwilioEmail(System.getenv("TWILIO_ACCOUNT_SID"), System.getenv("TWILIO_AUTH_TOKEN")); +``` + +This client has the same interface as the `SendGrid` client. diff --git a/use-cases/twilio-setup.md b/use-cases/twilio-setup.md new file mode 100644 index 00000000..7c3c37fc --- /dev/null +++ b/use-cases/twilio-setup.md @@ -0,0 +1,48 @@ +### 1. Obtain a Free Twilio Account + +Sign up for a free Twilio account [here](https://www.twilio.com/try-twilio?source=sendgrid-java). + +### 2. Set Up Your Environment Variables + +The Twilio API allows for authentication using with either an API key/secret or your Account SID/Auth Token. You can create an API key [here](https://twil.io/get-api-key) or obtain your Account SID and Auth Token [here](https://twil.io/console). + +Once you have those, follow the steps below based on your operating system. + +#### Linux/Mac + +```bash +echo "export TWILIO_API_KEY='YOUR_TWILIO_API_KEY'" > twilio.env +echo "export TWILIO_API_SECRET='YOUR_TWILIO_API_SECRET'" >> twilio.env +# or +echo "export TWILIO_ACCOUNT_SID='YOUR_TWILIO_ACCOUNT_SID'" > twilio.env +echo "export TWILIO_AUTH_TOKEN='YOUR_TWILIO_AUTH_TOKEN'" >> twilio.env +``` + +Then: + +```bash +echo "twilio.env" >> .gitignore +source ./twilio.env +``` + +#### Windows + +Temporarily set the environment variable (accessible only during the current CLI session): + +```bash +set TWILIO_API_KEY=YOUR_TWILIO_API_KEY +set TWILIO_API_SECRET=YOUR_TWILIO_API_SECRET +: or +set TWILIO_ACCOUNT_SID=YOUR_TWILIO_ACCOUNT_SID +set TWILIO_AUTH_TOKEN=YOUR_TWILIO_AUTH_TOKEN +``` + +Or permanently set the environment variable (accessible in all subsequent CLI sessions): + +```bash +setx TWILIO_API_KEY "YOUR_TWILIO_API_KEY" +setx TWILIO_API_SECRET "YOUR_TWILIO_API_SECRET" +: or +setx TWILIO_ACCOUNT_SID "YOUR_TWILIO_ACCOUNT_SID" +setx TWILIO_AUTH_TOKEN "YOUR_TWILIO_AUTH_TOKEN" +```