Skip to content

Instantly share code, notes, and snippets.

@jugyo
Last active Nov 26, 2020
Embed
What would you like to do?
An example to send email with Cloud Pub Sub and Cloud Functions #Rails
const sendEmail = require('./sendEmail').sendEmail;
/**
* Deplooyment:
*
* $ gcloud beta functions deploy sendEmail --trigger-topic sendEmail
*
*/
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event The Cloud Functions event.
* @param {!Function} The callback function.
*/
exports.sendEmail = (event, callback) => {
// The Cloud Pub/Sub Message object.
const pubsubMessage = event.data;
// We're just going to log the message to prove that
// it worked.
const decoded = Buffer.from(pubsubMessage.data, 'base64').toString();
console.log(decoded);
const data = JSON.parse(decoded);
sendEmail(data);
// Don't forget to call the callback.
callback();
};
require "google/cloud/pubsub"
#
# Configuration:
#
# environments/production.rb:
#
# Rails.application.configure do
# ...
# config.action_mailer.delivery_method = :pub_sub_mailer
# end
#
# initializers/pub_sub_mailer.rb:
#
# PubSubMailer.config = {
# project_id: ENV['GCLOUD_PROJECT_ID'],
# credentials: Rails.root.join('service-account-credentials.json')
# }
#
class PubSubMailer
class << self
attr_accessor :config
end
def initialize(options = {})
@pubsub = Google::Cloud::Pubsub.new(
project_id: self.class.config[:project_id],
credentials: self.class.config[:credentials]
)
end
def deliver!(mail)
data = {
to: Array(mail['to']).join(', '),
from: Array(mail['from']).join(', '),
cc: Array(mail['cc']).join(', '),
bcc: Array(mail['bcc']).join(', '),
reply_to: Array(mail['reply_to']).join(', '),
subject: mail.subject,
html: mail.decoded.to_s, # NOTE: Now only html is supported
}
@pubsub.topic('sendEmail').publish(data.to_json)
Rails.logger.debug(data)
rescue => e
# TODO: Notify the error
Rails.logger.error(e.message)
end
end
ActiveSupport.on_load :action_mailer do
ActionMailer::Base.add_delivery_method(
:pub_sub_mailer,
PubSubMailer
)
end
const nodemailer = require('nodemailer');
const smtpConfig = require('./smtp-config').config;
/**
* An example of the args
*
* { to: 'bob@example.com',
* from: 'example <noreply@example.com>',
* cc: '',
* bcc: '',
* reply_to: '',
* subject: 'Alice has sent a message to you!',
* text: 'text...',
* html: '<!DOCTYPE html>...' }
*/
exports.sendEmail = (mailOptions) => {
console.log('mailOptions', mailOptions);
var transporter = nodemailer.createTransport(smtpConfig);
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
exports.config = {
host: '',
port: 587,
secure: false,
requireTLS: true,
auth: {
user: 'user',
pass: 'pass'
}
};
@gadaldo
Copy link

gadaldo commented Sep 6, 2018

Nice. Though I am wondering how can I encrypt smtp configuration or if I can use AOuth2 authentication to send emails. Any suggestions?

@ivanrios
Copy link

ivanrios commented Nov 1, 2018

Of course, nodemailser module accepts AOuth2 and a lot of other type of services.

@randywu763
Copy link

randywu763 commented Aug 21, 2020

I tried to deploy this function but I get error message about function.js not found - can you give me detailed instructions on how to properly deploy this function? I am able to upload the ZIP file but I think I am missing something else?

@randywu763
Copy link

randywu763 commented Aug 22, 2020

randywu763@cloudshell:~ (mchpiotteam4)$ gcloud beta functions deploy sendEmail --trigger-topic sendEmail
Created .gcloudignore file. See gcloud topic gcloudignore for details.
Deploying function (may take a while - up to 2 minutes)...failed.
ERROR: (gcloud.beta.functions.deploy) OperationError: code=3, message=Build failed: function.js does not exist; Error ID: 7485c5b6
randywu763@cloudshell:~ (mchpiotteam4)$

@sidcool1234
Copy link

sidcool1234 commented Nov 26, 2020

Facing the same issue today. Anyone found the root cause?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment