SendGrid Examples

Does anyone have any examples of using SendGrid with api keys?

Hey rdagger.

While I’m not using Sendgrid, I’m sure it’s very similar to using Mailgun. This is my general setup:

I have a simple setup to build a subscriber list. When a subscriber signs up, they automatically receive an email.

Create a file called secrets.js (or something similar), gitignore it, and put your API keys in there:

process.env['MAILGUN_DOMAIN'] = "boundley.com";
process.env['MAILGUN_API_URL'] = "https://api.mailgun.net/v3";```

I created `mailgun.js` on the server side which houses all my `Meteor.methods`:


`Meteor.startup(function () {  
    Meteor.methods({
        // The initial Subscription Process, Sending the Email Address to Mailgun
        subscribe: function(email) {`
            
            // Make multiple requests faster
            this.unblock();

            // Define useful variables
            var mailinglist = 'news@boundley.com'
            var apiURL = 'https://api.mailgun.net/v3/lists/' + mailinglist + '/members' 
            var options = {
                auth:"api:" + process.env.MAILGUN_API_KEY,
                params: {
                    subscribed: true,
                    address: email,
                }
            }

            // What happens after the request has gotten a reply
            var onResult = function(error, result) {
                if(error){ 
                    console.log("Error: " + error)
                } else {
                    console.log("Subscription successful")
                }
            }

            // Make the actual request happen
            Meteor.http.post(apiURL, options, onResult)
        },
        
        
        // ***** Firing off the email to the new subscriber.
        emailSubscribed: function(email){
          
          this.unblock();
          
          var postURL = process.env.MAILGUN_API_URL + '/' + process.env.MAILGUN_DOMAIN + '/messages';
          var options = {
            auth: "api:" + process.env.MAILGUN_API_KEY,
            params: {
              "from" : "Boundley <boundley@boundley.com",
              "h:Reply-To" : "hello@boundley.com",
              "to" : email,
              "subject" : "Thanks For Subscribing To Boundley.com",
              "html" : "this is where the email content goes. can be formatted HTML and in-line styled. ",
            }
          }
          var onError = function(error, result) {
            if(error) {console.log("Error: " + error)}
          }
          
          Meteor.http.post(postURL, options, onError);
        },
    });
`});`

..Not really sure why my code is getting cut off. But you get the idea. All I have to do on the client side code is then pass in the input value (email address):

``Template.subscribeEmail.events({
    "submit .newsletter-form": function (event) {
      // Prevent default browser form submit
      event.preventDefault();``
 
      // Get value from form element
      var address = event.target.emailAddress.value;
      
      Meteor.call('subscribe', address);
      
      $("#subscribeModal").modal('hide');
      toastr.options.positionClass = "toast-top-center";
      toastr.success("You've been subscribed.", "Thank You!");
      
      Meteor.call('emailSubscribed', address)
    }
`});`

Hope that helps -- you can imitate this for building a simple email list and sending a welcome message, or re-purpose it for many other uses.





`

Is there any reason why you don’t just use the built in email package?
I’ve been using Mailgun from day 1 with the built in package and it works great out of the box for both text and html emails.

Hi there! I use Sendgrid, with the NPM package.
https://www.npmjs.com/package/sendgrid

It’s pretty easy and Sendgrid templates are very handy for transactional emails setup.

Here is an example code:


var sendgrid = Meteor.npmRequire( 'sendgrid' )( Meteor.settings.private.email.sendgrid.apiKey );

let sendSendgridEmail = ( templateId, emailAddr, subject, bodyVar, otherVars ) => {

	let email = new sendgrid.Email( {
		to: emailAddr,
		from: 'contact@example.com',
		subject: subject,
		html: bodyVar, // <%body%> tag for text, required 
		text: '' // <%body%> tag for html
	} );

	email.setFromName('Example');  // Optional
        
       // Merge variables in template if any 
	_.each( otherVars, function ( el ) {
		for( key in el ) {
			if( el.hasOwnProperty( key ) ) {
				var value = el[ key ];
				email.addSubstitution( key, value );
			}
		}
	} );


	// https://sendgrid.com/docs/API_Reference/SMTP_API/apps.html#template
	email.addFilter( 'templates', 'template_id', templateId );

	sendgrid.send( email, function ( err, response ) {
		if( err ) {
			return console.error( err );
		}
		console.log( response ); // Success message
	} );
};

Thanks, that helped me fix the problem.

I will be sending a high volume of email using templates and to multiple recipients at a time. Mailgun seems comparable to SendGrid. I found slightly more positive reviews for SendGrid and they have great documentation. I also plan on using their api to hook incoming emails.

In case anyone is interested, I was also able to get the Meteor Email package working with SendGrid using an api key instead of credentials:

    Meteor.startup(function () {
        process.env.MAIL_URL = 'smtp://apikey:' + 
            Meteor.settings.SendGridApiKey + 
            '@smtp.sendgrid.net:587';
    });

Where SendGridApiKey is your SendGrid api key specified in settings.json.

Thanks @rdagger, I’m just in the process of switching to the SendGrid ApiKey from username/password (required by December 9th), and I’m nervous of screwing it up and pissing users of my application off.

Just to be clear, I would put your code in the server folder (with the SendGridApiKey) … and also the SendGridApiKey in settings.json (where I currently have the username/password?

Sorry, if this is an obvious question, but I just want to be 100% sure.

Thanks in advance - Bob

@blorriman It’s been 4 years since I used Meteor but yes I think I put the above code in server startup and the key went in settings.json. Please make sure settings.json is added to .gitignore.

Thanks - I’ll give it a try

Hey there, were you able to get this to work? When I try @rdagger 's approach, keep getting:

Error: Invalid login: 501 Username used for auth is not valid email address

Looks like meteor wants an email for username, but Sendgrid tells us to use “apikey” as username. Any ideas?

If you’ve updated your packages then it sounds like it’s briked. That sucks… Sorry to hear that’s happened. File upload is also the same. No one ever checks