public static void main(String[] args) throws SendGridException { SendGrid sendgrid = new SendGrid(SENDGRID_API_KEY); SendGrid.Email email = new SendGrid.Email(); email.addTo(TO_EMAIL); email.setFrom(SENDGRID_SENDER); email.setSubject("This is a test email"); email.setText("Example text body."); SendGrid.Response response = sendgrid.send(email); if (response.getCode() != 200) { System.out.print(String.format("An error occured: %s", response.getMessage())); return; } System.out.print("Email sent."); }
/** * 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(Request request) { this.attempt(request, new APICallback() { @Override public void error(Exception ex) { } public void response(Response r) { } }); }
/** * Remove a request header. * @param key the header key to remove. * @return the new set of request headers. */ public Map<String, String> removeRequestHeader(String key) { this.requestHeaders.remove(key); return getRequestHeaders(); }
private void initSendGridClient() { if (delegate == null) { if(username!=null && password!=null) { delegate = new SendGrid(username, password); } else if(apiKey!=null) { delegate = new SendGrid(apiKey); } else { throw new IllegalStateException("No SendGrid instance available. Either provide an instance manually or provide username/password or provide API key"); } } }
@Override public void send(final Email email) throws SendGridException { if (email == null) { throw new IllegalArgumentException("[email] cannot be null"); } LOG.debug("Sending to SendGrid client: FROM {}<{}>", email.getFromName(), email.getFrom()); LOG.debug("Sending to SendGrid client: TO {} (as {})", email.getTos(), email.getToNames()); LOG.debug("Sending to SendGrid client: SUBJECT {}", email.getSubject()); LOG.debug("Sending to SendGrid client: TEXT CONTENT {}", email.getText()); LOG.debug("Sending to SendGrid client: HTML CONTENT {}", email.getHtml()); initSendGridClient(); final SendGrid.Response response = delegate.send(email); if (response.getStatus()) { LOG.debug("Response from SendGrid client: ({}) {}", response.getCode(), response.getMessage()); } else { throw new SendGridException(new IOException("Sending to SendGrid failed: (" + response.getCode() + ") " + response.getMessage())); } }
@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)); } });
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); } }
mail.addContent(content); SendGrid sg = new SendGrid(apiKey); Request request = new Request(); try { request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); log.info("Status Code: {}", String.valueOf(response.getStatusCode())); log.info("Body: {}", response.getBody());
public EmailSendGridNotificationHandler(MxisdConfig mCfg, EmailSendGridConfig cfg) { super(mCfg.getMatrix(), mCfg.getServer()); this.cfg = cfg.build(); this.sendgrid = new SendGrid(cfg.getApi().getKey()); }
private void send(String recipient, Email email) { if (StringUtils.isBlank(cfg.getIdentity().getFrom())) { throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " + "You must set a value for notifications to work"); } try { email.addTo(recipient); email.setFrom(cfg.getIdentity().getFrom()); email.setFromName(cfg.getIdentity().getName()); Response response = sendgrid.send(email); if (response.getStatus()) { log.info("Successfully sent email to {} using SendGrid", recipient); } else { throw new RuntimeException("Error sending via SendGrid to " + recipient + ": " + response.getMessage()); } } catch (SendGridException e) { throw new RuntimeException("Unable to send e-mail invite via SendGrid to " + recipient, e); } }
@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)); } });
import com.sendgrid.*; public class SendGridExample { public static void main(String[] args) { SendGrid sendgrid = new SendGrid("SENDGRID_APIKEY"); SendGrid.Email email = new SendGrid.Email(); email.addTo("test@sendgrid.com"); email.setFrom("you@youremail.com"); email.setSubject("Sending with SendGrid is Fun"); email.setHtml("and easy to do anywhere, even with Java"); SendGrid.Response response = sendgrid.send(email); } }
/** * Add a new request header. * @param key the header key. * @param value the header value. * @return the new set of request headers. */ public Map<String, String> addRequestHeader(String key, String value) { this.requestHeaders.put(key, value); return getRequestHeaders(); }
/** * 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(Request request) { this.attempt(request, new APICallback() { @Override public void error(Exception ex) { } public void response(Response r) { } }); }
SendGrid sendgrid = new SendGrid("YOUR_API_KEY_HERE"); SendGrid.Email welcomeMail = new SendGrid.Email(); welcomeMail.addTo(emailAddress); welcomeMail.addToName("User-san"); welcomeMail.setFrom("welcome@example.com"); welcomeMail.setSubject("Welcome to Example!"); welcomeMail.setText("Thank you for your interest in Example.com! It is still in Beta at the moment but there are a number of exciting features planned. Tell us what you'd like to see."); try { SendGrid.Response response = sendgrid.send(welcomeMail); System.out.println(response.getMessage()); } catch (SendGridException sge) { sge.printStackTrace(); }
/** * Remove a request header. * @param key the header key to remove. * @return the new set of request headers. */ public Map<String, String> removeRequestHeader(String key) { this.requestHeaders.remove(key); return getRequestHeaders(); }
@Override protected Void doInBackground(Void... params) { try { SendGrid sendgrid = new SendGrid(SENDGRID_USERNAME, SENDGRID_PASSWORD); SendGrid.Email email = new SendGrid.Email(); // Get values from edit text to compose email // TODO: Validate edit texts email.addTo(mTo); email.setFrom(mFrom); email.setSubject(mSubject); email.setText(mText); // Attach image if (mUri != null) { email.addAttachment(mAttachmentName, mAppContext.getContentResolver().openInputStream(mUri)); } // Send email, execute http request SendGrid.Response response = sendgrid.send(email); mMsgResponse = response.getMessage(); Log.d("SendAppExample", mMsgResponse); } catch (SendGridException | IOException e) { Log.e("SendAppExample", e.toString()); } return null; }
/** * Add a new request header. * @param key the header key. * @param value the header value. * @return the new set of request headers. */ public Map<String, String> addRequestHeader(String key, String value) { this.requestHeaders.put(key, value); return getRequestHeaders(); }