Giter Site home page Giter Site logo

sendgrid / sendgrid-java Goto Github PK

View Code? Open in Web Editor NEW
482.0 225.0 406.0 5.96 MB

The Official Twilio SendGrid Led, Community Driven Java API Library

Home Page: https://sendgrid.com

License: MIT License

Java 99.32% Dockerfile 0.28% Makefile 0.40%
java sendgrid email transactional-emails

sendgrid-java's Introduction

SendGrid Logo

BuildStatus Maven Central Twitter Follow GitHub contributors Open Source Helpers MIT licensed

This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via Java.

Version 3.X.X of this library provides full support for all Twilio SendGrid Web API v3 endpoints, including the new v3 /mail/send.

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 and pull requests or simply upvote or comment on existing issues or pull requests.

If you need help using SendGrid, please check the Twilio SendGrid Support Help Center.

Table of Contents

Installation

Prerequisites

  • Java 8 or 11
  • The Twilio SendGrid service, starting at the free level to send up to 40,000 emails for the first 30 days, then send 100 emails/day free forever or check out our pricing.

Setup Environment Variables

Update the development environment with your SENDGRID_API_KEY, for example:

  1. Copy the sample environment file to a new file
cp .env_sample .env
  1. Edit the new .env to add your API key
  2. Source the .env file to set the variable in the current session
source .env

Install Package

Choose your installation method - Maven w/ Gradle (recommended), Maven or Jar file.

via Maven w/ Gradle

Add the following to your build.gradle file in the root of your project.

...
dependencies {
  ...
  implementation 'com.sendgrid:sendgrid-java:4.10.2'
}

repositories {
  mavenCentral()
}
...

via Maven

mvn install

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

Dependencies

Quick Start

Hello Email

The following is the minimum needed code to send an email with the /mail/send Helper (here is a full example):

With Mail Helper Class

import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("[email protected]");
    String subject = "Sending with Twilio SendGrid is Fun";
    Email to = new Email("[email protected]");
    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;
    }
  }
}

The Mail constructor creates a personalization object for you. Here is an example of how to add to it.

Without Mail Helper Class

The following is the minimum needed code to send an email without the /mail/send Helper (here is a full example):

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\":\"[email protected]\"}],\"subject\":\"Sending with Twilio SendGrid is Fun\"}],\"from\":{\"email\":\"[email protected]\"},\"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;
    }
  }
}

General v3 Web API Usage

import com.sendgrid.*;
import java.io.IOException;

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;
    }
  }
}

Usage

Use Cases

Examples of common API use cases, such as how to send an email with a transactional template.

Announcements

All updates to this library are documented in our CHANGELOG and releases.

How to Contribute

We encourage contribution to our libraries (you might even score some nifty swag), please see our CONTRIBUTING guide for details.

Quick links:

Troubleshooting

Please see our troubleshooting guide for common library issues.

About

sendgrid-java is maintained and funded by Twilio SendGrid, Inc. The names and logos for sendgrid-java are trademarks of Twilio SendGrid, Inc.

Support

If you need help installing or using the library, please check the Twilio SendGrid Support Help Center.

License

The MIT License (MIT)

sendgrid-java's People

Contributors

af4ro avatar andy-trimble avatar bharatr21 avatar brandonmwest avatar ciceropablo avatar crweiner avatar dependabot[bot] avatar derjayjay avatar diegoc-am avatar dmitraver avatar eddiezane avatar eshanholtz avatar huytranrjc avatar jennifermah avatar luan-cestari avatar mbernier avatar mithunsasidharan avatar motdotla avatar mptap avatar nquinlan avatar p3trur0 avatar pushkyn avatar rohantalip avatar sccalabr avatar seanstaley avatar shashank135sharma avatar shwetha-manvinkurke avatar thinkingserious avatar twilio-ci avatar twilio-dx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sendgrid-java's Issues

Spanish characters not encoded properly in both the email header and in the actual content

Hello everyone,

One of our customers, who uses the most recent version of this library, encounters the following issue:

  • when using Korean / Japanese characters within the SMTPAPI header ( without them being previously encoded ) the library works ok, but when they wish to use Spanish characters ( also without encoding ) - e.g. ñ - and when such a character is being usesd, the below error occurs:

code=400 message={"message": "error", "errors": ["JSON in x-smtpapi could not be parsed"]}

  • this is the request the customers makes:

email.getSMTPAPI().jsonString() ->

{"category":["Message:TestMessageSPANISH","Group:Content updates & Invitations","CampaignHistory:43667","CampaignSchedule:412","Campaign:Test Refactoring"],"sub":{"%@name@%":["gianne.tan+2014111901","test - \uf1"]},"unique_args":{"campaignHistoryID":"43667","accountID":"[ACCOUNTID]","messageID":"2406","messageGroupID":"10","messageTemplateID":"1455"}}

Note: ñ was encoded to \uf1

  • this issue seems to happen only for Spanish characters.

Please let me know if additional details should be requested from the client. Thank you!

senggrid is not supported in java1.6

I am trying with all the version of sendgrid(sendgrid-java-0.3.0.jar,smtpapi-java-0.0.1.jar and smtpapi-java-0.0.2.jar,sendgrid-java-1.1.2.jar) in my application but am getting the following exception
in my machine it having java 1.6

java.lang.UnsupportedClassVersionError: com/sendgrid/SendGridException : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Exception in thread "main"

proper setting of subjectLine for special characters

Hi,

I am trying to send an emails in Korean language with subjectLines having substitution tokens/tags specified through xsmtpapi. Most of the time there is no problem in the received email. But for this specific subjectLine "알림 : 고객님의 레벨 테스트가 (%@LOCALESCHEDULE@%) 에 다시 진행 될 예정입니다 - DEV" in which %@LOCALESCHEDULE@% is the substitution token/tag, the token was not replaced. It seems that the cause is the subjectLine is being cut on the token part as seen in the resulting encoding below.:

=?UTF-8?Q?=EC=95=8C=EB=A6=BC_:=EA=B3=A0=EA=B0=9D?=
=?UTF-8?Q?=EB=8B=98=EC=9D=98
=EB=A0=88=EB=B2=A8_=ED=85=8C=EC=8A=A4?=
=?UTF-8?Q?=ED=8A=B8=EA=B0=80_%@LOCALESCHE?=
=?UTF-8?Q?DULE@%=EC=97=90=EB=8B=A4=EC=8B=9C_=EC=A7=84=ED=96=89_?=
=?UTF-8?Q?=EB=90=A0_=EC=98=88=EC=A0=95=EC=9E=85=EB=8B=88=EB=8B=A4._-__DEV?=

I then added line breaks after each space found in the subject line before doing sendgrid.setSubject. The specific subjectLine was then processed successfully.

However, my other emails that uses pure ASCII character as subject line was not any more received properly by the recipients. As inquired by sendgrid, there was no xsmtpapi header received on such emails. I resolved to only add line break if there are non-ASCII characters in the subject line. Otherwise, retain the original subjectLine.

Can the SendGrid API handle this case automatically? Or are there specifications on constructing a valid subjectLine - normal characters or with special characters?

new SendGrid(apikey)

Hello,

a question regarding best practises and performance.

Would it be better to initialise a new SendGrid instance for every email or would it be better to make single instance that is reused throughout the application's life ?

Kind regards

Pishty

Is the SendGrid class thread-safe?

I've created a single SendGrid bean in Spring to be injected in my app, and multiple threads will be calling SendGrid.send(). From what I can see this should be safe, since the only instance variable used in send() is the HttpClient, which according to the docs should be thread-safe. But it would be good to get this confirmed, in case there's some other mutable state that I missed.

Add attachment with contents from String.

Hi there.

There is no way to add an attachment where the contents of the attachment comes from a string. So far, it needs to be flushed to disk, which is impossible on Google App Engine.

sendgrid-java requires Java7 - com/github/sendgrid/SendGrid : Unsupported major.minor version 51.0

Tried to test latest sendgrid-java 0.1.2 under Java 6 (sorry, our production is still on Java-6).

Hello SendGrid
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/github/sendgrid/SendGrid : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at SendGridEmailer$.sendTest(SendGridEmailer.scala:32)
at SendGridTest$delayedInit$body.apply(SendGridTest.scala:5)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at SendGridTest$.main(SendGridTest.scala:1)
at SendGridTest.main(SendGridTest.scala)

Add check to see if submission was done correctly

So far there is no checks in the code for errors. Sending an email with no subject is blindly accepted. What about adding a check like:

if(!request.ok())
throw new RuntimeException(request.body());

in the web() method?

Documentation for Headers

The ReadMe gives the following example for adding a custom header:

sendgrid.addHeader("category", "My New Category");

That example can give the impression that we are assigning a category to the email that can be tracked through SendGrid, when in reality it is just adding a customer header to the message. To add a category to the message, it should be added via the SMTP API header:

sendgrid.addHeader("X-SMTPAPI", "{\"category\":\"My New Category\"}");

Documentation should be updated to reduce confusion - perhaps giving an example of a custom header like:

sendgrid.addHeader("X-Sent-Using", "SendGrid-API")

java.lang.NoSuchFieldError: INSTANCE

Hi,
I imported the jar sendgrid-java.jar and then tested the sendgridexample.java. I get the following error, Not sure how to move forward
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:52)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:56)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:46)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:72)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:84)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:59)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$InternalConnectionFactory.(PoolingHttpClientConnectionManager.java:493)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:149)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:138)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:114)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:726)
at com.sendgrid.SendGrid.(SendGrid.java:59)
at com.arches.radius.email.SendGridEmail.main(SendGridEmail.java:16)
Java Result: 1

Following is the code

import com.sendgrid.*;
public class SendGridEmail {

public static void main(String[] args) {
SendGrid sendgrid = new SendGrid("XXXXXXXXXXXX", "XXXXXXXXXXXXXXXX");

SendGrid.Email email = new SendGrid.Email();
email.addTo("XXXXXXXXXXXXX");
email.setFrom("XXXXXXXXXXXXXXXXXX");
email.setSubject("Hello World");
email.setText("My first email with SendGrid Java!");

try {
  SendGrid.Response response = sendgrid.send(email);
  System.out.println(response.getMessage());
}
catch (SendGridException e) {
  System.err.println(e);
}

}

}

To, ToName and Substitution values getting jumbled.

Hi,

Currently the curl command which is getting framed by this framework is something like this
api_user=XXXXXX&api_key=XXXXXX&to[0]=[email protected]&to[1]=[email protected]&to[2]= [email protected]&toname[1]=sunand&toname[2]=sp&toname[3]=samosa&x-smtpapi={"sub":{"there":["Sunand Online","SP","Samosa Chat"]}}&subject=Hello there&text=Hi there&html=Hi there, How are you?&from=[email protected]

This is wrong, this is getting re-ordered at the sendgrid end it sends wrong Substitution values to recipients and also sets incorrect to and toname combination

The correct one is below, we should not specify to[1] and toname[1]
api_user=XXXXXX&api_key=XXXXXX&to[]=[email protected]&to[]=[email protected]&to[]= [email protected]&toname[]=sunand&toname[]=sp&toname[]=samosa&x-smtpapi={"sub":{"there":["Sunand Online","SP","Samosa Chat"]}}&subject=Hello there&text=Hi there&html=Hi there, How are you?&from=[email protected]

This should be fixed in buildingEmailBody.

413 Request Entity Too Large

Similar production issue to the one posted here (sendgrid/sendgrid-php#148), although not with sendgrid-php. This particular email was to a single user with a body size of 6791 characters, using the sendgrid java lib, via the X-SMTPAPI, and the message was well-formed. Response from Sendgrid is "413 Request Entity Too Large". Please advise as to whom I should route this issue to, the ETA of a fix and / or documentation on the maximum message size that Sendgrid can handle.

Continuation of issue #62

I was only able to test issue #62 now but the problem still remains with extended latin 1 characters.

Instead of Umlauts use the following String: "¥ÄþĈĦƂǂdžǓǥȉțȤȰȴẛʒΦλ" on a substitution and it shall fail.

NoSuchFieldError: INSTANCE] with root cause

When trying to send an email via the Java client library, I am getting the following error:

NoSuchFieldError: INSTANCE] with root cause
java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.conn.HttpClientConnectionOperator.(HttpClientConnectionOperator.java:74)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:151)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:138)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:114)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:726)
at com.sendgrid.SendGrid.(SendGrid.java:59)

Note that I am dumping the name of the class being loaded by the classloader prior to creating an instance of the SendGrid. See below

ClassLoader classLoader = SendGridPasswordResetEmail.class.getClassLoader();
URL resource = classLoader.getResource("org/apache/http/impl/conn/HttpClientConnectionOperator.class");
System.out.println(resource);

The output shows that it is loading the correct class (see below)

..../tagitlabs/build/web/WEB-INF/lib/sendgrid-java.jar!/org/apache/http/impl/conn/HttpClientConnectionOperator.class

Not able to import sendgrid-java-1.2.0.jar successfully

[error] Class org.apache.http.impl.client.CloseableHttpClient not found - continuing with a stub.
[error] error while loading SendGrid, class file '/Users/devendra/.m2/repository/com/sendgrid/sendgrid-java/1.2.0/sendgrid-java-1.2.0.jar(com/sendgrid/SendGrid.class)' is broken
[error](class java.lang.NullPointerException/null)

This is the error I am getting adding sendGrid as a dependency to my application module

Appreciate if you let me know if I am missing something

Crash on email.addTo("[email protected]);

Constantly crashes when I try to add an email address.
I'm using Android Studio beta 0.8.2 with the SendGrid gradle dependency.

07-15 15:56:21.872 14646-14646/com.package.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.package.myapp, PID: 14646
java.lang.NoSuchMethodError: org.json.JSONObject.append
at com.sendgrid.smtpapi.SMTPAPI.addTo(SMTPAPI.java:31)
at com.sendgrid.SendGrid$Email.addTo(SendGrid.java:86)
at com.package.myapp.activity.SendEmailActivity.onCreate(SendEmailActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

HttpProxy

Hi there,

it would be nice if you could add the ability to use sendgrid trough a proxy server.

I already did this with something like:

sendgrid = new SendGrid("user", "password");
HttpHost proxy = new HttpHost("server",3128);
CloseableHttpClient http = HttpClientBuilder.create().setProxy(proxy).setUserAgent("sendgrid/" + sendgrid.getVersion() + ";java").build();
sendgrid = sendgrid.setClient(http);

Substitutions not respecting non ASCII characters

The issue reported here: (#57) is still occurring on latest version.

I don't think the code committed ever fixed the issue.

How to reproduce:

1.Create a template on sendgrid.com
2.Use it from a java app and in the substitution add both a Umlaut: ï and a ß.
3.Check if the received email contains these characters.

In my case I get a i instead of a ï and a \u00DF instead of a ß.

sendAt issue

I tried using the sendat function to schedule an email but doesn’t seem to be working correctly. I set the time for 5:05 PM EST, however I received an email at 5:04 PM It seems like it was sent immediately and sendat was ignored. Following is the code

public static void main(String[] args) {
try {
String dateString = "Fri, 03 Apr 2015 05:05:18 EST";
DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");
Date date = dateFormat.parse(dateString);
long unixTime = (long)date.getTime()/1000;
System.out.println(unixTime); //<- prints 1428055518

SendGrid sendgrid = new SendGrid("ARCHES", "XXXXXXXXXXXXXXXXXXXXXXXXXXXX");

SendGrid.Email email = new SendGrid.Email();
email.addTo("[email protected]");
email.setFrom("[email protected]");
email.setSubject("Hello World");
email.setText("My first email with SendGrid Java!");
email.setSendAt((int)unixTime);



  SendGrid.Response response = sendgrid.send(email);
  System.out.println(response.getMessage());
}
catch (SendGridException e) {
  System.err.println(e);
}
catch (Exception e) {
  System.err.println(e);
}

}

Thanks
Yogesh

Expose Http Connection parameters

In high load apps the SendGrid client may not work as expected. The httpclient that is built uses defaults for everything. You may want to have a constructor where the user passes their own HttpClient.
Javadoc states this when using defaults for HttpClient:

ClientConnectionPoolManager maintains a pool of org.apache.http.HttpClientConnections and is able to service connection requests from multiple execution threads. Connections are pooled on a per route basis. A request for a route which already the manager has persistent connections for available in the pool will be services by leasing a connection from the pool rather than creating a brand new connection.
ClientConnectionPoolManager maintains a maximum limit of connection on a per route basis and in total. Per default this implementation will create no more than than 2 concurrent connections per given route and no more 20 connections in total. For many real-world applications these limits may prove too constraining, especially if they use HTTP as a transport protocol for their services. Connection limits, however, can be adjusted using org.apache.http.pool.ConnPoolControl methods.

add mail object

adding a "friendly issue" as per hipchat.

all our other libraries have a mail object which is initialized and then sent with, however, in the java library, we don't yet have this concept

Java lib is desconsidering break lines in text content

Hi, I'm sending an email with the text content:

Hello,\n\nThis is a test message from SendGrid. We have sent this to you because you requested a test message be sent from your account.\n\nThis is a link to google.com: google.com\nthis is a link to apple.com: apple.com\nthis is a link to sendgrid.com: sendgrid.com\n\nthank you for reading this test message.\n\nLove,\nYour friends at SendGrid

The expected result was:

Hello,

This is a test message from SendGrid. We have sent this to you because you requested a test message be sent from your account.

This is a link to google.com: google.com
this is a link to apple.com: apple.com
this is a link to sendgrid.com: sendgrid.com

thank you for reading this test message.

Love,
Your friends at SendGrid

But the result was:

Hello,

This is a test message from SendGrid. We have sent this to you because you requested a test message be sent from your account.

This is a link to google.com: google.com this is a link to apple.com: apple.com this is a link to sendgrid.com: sendgrid.com

thank you for reading this test message.

Love, Your friends at SendGrid

Some break lines are being ignored.

I've tested with the versions 1.1.0 and 2.2.2.

sendgrid-java faulty unicode escaping

sendgrid-java is still failing when the substitutions have non-latin characters.

I've traced the issue to the SMTPAPI.escapeUnicode(String) method.

sendgrid-java still uses an older version of smtpapi-java:(1.1.0). The newer vesion of smtpapi-java(1.1.1) might have that method fixed.

Please make sure that smtpapi-java has the updated SMTPAPI.escapeUnicodeMethod() and update the version in sendgrid-java. https://github.com/sendgrid/sendgrid-java/blob/master/build.gradle#L48

org.json.chargebee-1.0 should be listed as dependency on main page

I am copying + pasting Sendgrid.java in my project

The build script lists this as compile dependency
org.json:org.json:chargebee-1.0

However on the main page - there is no allusion to this fact. As you are aware, there are many different implementation of JSON libraries in Java so this dependency should be listed clearly.

Android Support

Hi,

I am using Sendgrid in my Android app with Android Studio, I imported it by adding:
compile 'com.sendgrid:sendgrid-java:2.2.1'

and the app crashes with the error:
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/HttpClientBuilder; at com.sendgrid.SendGrid.<init>(SendGrid.java:67)

It's very similar with this : http://stackoverflow.com/questions/30284213/sendgrid-java-not-working-in-maven

Then I add httpclient dependency for Android:
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

The error is gone but got new error:

Information:Gradle tasks [:evercamPlay:assembleDebug]
WARNING [Project: :evercamPlay] Current NDK support is deprecated.  Alternative will be provided in the future.
Warning:Dependency org.apache.httpcomponents:httpclient:4.3.4 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
Warning:Dependency org.json:json:20140107 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage with jarjar to change the class packages
Warning:Dependency org.json:json:20140107 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage with jarjar to change the class packages
Warning:Dependency org.apache.httpcomponents:httpclient:4.3.4 is ignored for debug as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
Warning:Dependency org.apache.httpcomponents:httpclient:4.3.4 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
Warning:Dependency org.json:json:20140107 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage with jarjar to change the class packages
Warning:Dependency org.json:json:20140107 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage with jarjar to change the class packages
Warning:Dependency org.apache.httpcomponents:httpclient:4.3.4 is ignored for release as it may be conflicting with the internal version provided by Android.
         In case of problem, please repackage it with jarjar to change the class packages
......
Error:Execution failed for task ':evercamPlay:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: org/apache/http/concurrent/Cancellable.class
Information:BUILD FAILED

I wonder does sendgrid-java officially supports Android? Or is there any possible solutions?

Thanks a lot!
Liuting

jar file says package does not exist

i downloaded the code as a zip file and run
gradlew build
It created 4 jar files.
I imported the sendgird 1.2.0-jar.jar in a project of mine in netbeans 8.0 (java 8)

when I run SendGrid.Email email = new SendGrid.Email();
I got the following exception:

Exception in thread "main" java.lang.ExceptionInInitializerError
at xyz.Main.main(Main.java:84)
Caused by: java.lang.RuntimeException: Uncompilable source code - package org.json does not exist
at com.sendgrid.SendGrid$Email.(SendGrid.java:3)

If I browse the contents of the jar file, i see that the package does indeed exist. I don't understand why this exception appears

API Built For Java 7

I'm trying to run the library in a Java 6 Runtime and getting an UnsupportedClassVersionError. Looking at the code, I don't see anything that would preclude the library from being built for Java 6 (or earlier). It seems like a good practice to build for the earliest version of Java that your library would support.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.