add an email service

This commit is contained in:
Asim Aslam
2021-07-01 12:37:12 +01:00
parent 97298b9cfb
commit eb0165f4bf
11 changed files with 567 additions and 0 deletions

2
email/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
emails

3
email/Dockerfile Normal file
View File

@@ -0,0 +1,3 @@
FROM alpine
ADD email /email
ENTRYPOINT [ "/email" ]

22
email/Makefile Normal file
View File

@@ -0,0 +1,22 @@
GOPATH:=$(shell go env GOPATH)
.PHONY: init
init:
go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
go get github.com/micro/micro/v3/cmd/protoc-gen-micro
.PHONY: proto
proto:
protoc --proto_path=. --micro_out=. --go_out=:. proto/email.proto
.PHONY: build
build:
go build -o email *.go
.PHONY: test
test:
go test -v ./... -cover
.PHONY: docker
docker:
docker build . -t email:latest

8
email/README.md Normal file
View File

@@ -0,0 +1,8 @@
Send emails in a flash
# Emails Service
A quick and easy email api. Simply provide a from, to and text or html body.
Powered by [Sendgrid](https://sendgrid.com)

3
email/generate.go Normal file
View File

@@ -0,0 +1,3 @@
package main
//go:generate make proto

130
email/handler/email.go Normal file
View File

@@ -0,0 +1,130 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/micro/micro/v3/service/config"
"github.com/micro/micro/v3/service/errors"
log "github.com/micro/micro/v3/service/logger"
pb "github.com/micro/services/email/proto"
)
type sendgridConf struct {
Key string `json:"key"`
EmailFrom string `json:"email_from"`
}
func NewEmailHandler() *Email {
c := sendgridConf{}
val, err := config.Get("sendgridapi")
if err != nil {
log.Warnf("Error getting config: %v", err)
}
err = val.Scan(&c)
if err != nil {
log.Warnf("Error scanning config: %v", err)
}
if len(c.Key) == 0 {
log.Fatalf("Sendgrid API key not configured")
}
return &Email{
c,
}
}
type Email struct {
config sendgridConf
}
func (e *Email) Send(ctx context.Context, request *pb.SendRequest, response *pb.SendResponse) error {
if len(request.From) == 0 {
return errors.BadRequest("email.send.validation", "Missing from address")
}
if len(request.To) == 0 {
return errors.BadRequest("email.send.validation", "Missing to address")
}
if len(request.Subject) == 0 {
return errors.BadRequest("email.send.validation", "Missing subject")
}
if len(request.TextBody) == 0 && len(request.HtmlBody) == 0 {
return errors.BadRequest("email.send.validation", "Missing email body")
}
if err := e.sendEmail(request); err != nil {
log.Errorf("Error sending email: %v\n", err)
return errors.InternalServerError("email.sendemail", "Error sending email")
}
return nil
}
// sendEmail sends an email invite via the sendgrid API using the
// pre-designed email template. Docs: https://bit.ly/2VYPQD1
func (e *Email) sendEmail(req *pb.SendRequest) error {
content := []interface{}{}
if len(req.TextBody) > 0 {
content = append(content, map[string]string{
"type": "text/plain",
"value": req.TextBody,
})
}
if len(req.HtmlBody) > 0 {
content = append(content, map[string]string{
"type": "text/html",
"value": req.HtmlBody,
})
}
reqBody, _ := json.Marshal(map[string]interface{}{
"from": map[string]string{
"email": e.config.EmailFrom,
"name": req.From,
},
"reply_to": map[string]string{
"email": e.config.EmailFrom,
"name": req.From,
},
"subject": req.Subject,
"content": content,
"personalizations": []interface{}{
map[string]interface{}{
"to": []map[string]string{
{
"email": req.To,
},
},
},
},
})
httpReq, err := http.NewRequest("POST", "https://api.sendgrid.com/v3/mail/send", bytes.NewBuffer(reqBody))
if err != nil {
return err
}
httpReq.Header.Set("Authorization", "Bearer "+e.config.Key)
httpReq.Header.Set("Content-Type", "application/json")
rsp, err := new(http.Client).Do(httpReq)
if err != nil {
return fmt.Errorf("could not send email, error: %v", err)
}
defer rsp.Body.Close()
if rsp.StatusCode < 200 || rsp.StatusCode > 299 {
bytes, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return err
}
return fmt.Errorf("could not send email, error: %v", string(bytes))
}
return nil
}

27
email/main.go Normal file
View File

@@ -0,0 +1,27 @@
package main
import (
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/logger"
"github.com/micro/services/email/handler"
pb "github.com/micro/services/email/proto"
"github.com/micro/services/pkg/tracing"
)
func main() {
// Create service
srv := service.New(
service.Name("email"),
service.Version("latest"),
)
// Register handler
pb.RegisterEmailHandler(srv.Server(), handler.NewEmailHandler())
traceCloser := tracing.SetupOpentracing("email")
defer traceCloser.Close()
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}

244
email/proto/email.pb.go Normal file
View File

@@ -0,0 +1,244 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.15.6
// source: proto/email.proto
package email
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// Send an email by passing in from, to, subject and a text or html body
type SendRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// the name of the sender, can be email or name
From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"`
// the email address of the recipient
To string `protobuf:"bytes,2,opt,name=to,proto3" json:"to,omitempty"`
// the email subject
Subject string `protobuf:"bytes,3,opt,name=subject,proto3" json:"subject,omitempty"`
// the text body
TextBody string `protobuf:"bytes,4,opt,name=text_body,json=textBody,proto3" json:"text_body,omitempty"`
// the html body
HtmlBody string `protobuf:"bytes,5,opt,name=html_body,json=htmlBody,proto3" json:"html_body,omitempty"`
}
func (x *SendRequest) Reset() {
*x = SendRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_email_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SendRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SendRequest) ProtoMessage() {}
func (x *SendRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_email_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SendRequest.ProtoReflect.Descriptor instead.
func (*SendRequest) Descriptor() ([]byte, []int) {
return file_proto_email_proto_rawDescGZIP(), []int{0}
}
func (x *SendRequest) GetFrom() string {
if x != nil {
return x.From
}
return ""
}
func (x *SendRequest) GetTo() string {
if x != nil {
return x.To
}
return ""
}
func (x *SendRequest) GetSubject() string {
if x != nil {
return x.Subject
}
return ""
}
func (x *SendRequest) GetTextBody() string {
if x != nil {
return x.TextBody
}
return ""
}
func (x *SendRequest) GetHtmlBody() string {
if x != nil {
return x.HtmlBody
}
return ""
}
type SendResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *SendResponse) Reset() {
*x = SendResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_email_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SendResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SendResponse) ProtoMessage() {}
func (x *SendResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_email_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SendResponse.ProtoReflect.Descriptor instead.
func (*SendResponse) Descriptor() ([]byte, []int) {
return file_proto_email_proto_rawDescGZIP(), []int{1}
}
var File_proto_email_proto protoreflect.FileDescriptor
var file_proto_email_proto_rawDesc = []byte{
0x0a, 0x11, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x22, 0x85, 0x01, 0x0a, 0x0b, 0x53,
0x65, 0x6e, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x66, 0x72,
0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x12, 0x0e,
0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x74, 0x6f, 0x12, 0x18,
0x0a, 0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
0x07, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x65, 0x78, 0x74,
0x5f, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x74, 0x65, 0x78,
0x74, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x1b, 0x0a, 0x09, 0x68, 0x74, 0x6d, 0x6c, 0x5f, 0x62, 0x6f,
0x64, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x68, 0x74, 0x6d, 0x6c, 0x42, 0x6f,
0x64, 0x79, 0x22, 0x0e, 0x0a, 0x0c, 0x53, 0x65, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x32, 0x3a, 0x0a, 0x05, 0x45, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x31, 0x0a, 0x04, 0x53,
0x65, 0x6e, 0x64, 0x12, 0x12, 0x2e, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x2e, 0x53, 0x65, 0x6e, 0x64,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x2e,
0x53, 0x65, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x0f,
0x5a, 0x0d, 0x2e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x3b, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_proto_email_proto_rawDescOnce sync.Once
file_proto_email_proto_rawDescData = file_proto_email_proto_rawDesc
)
func file_proto_email_proto_rawDescGZIP() []byte {
file_proto_email_proto_rawDescOnce.Do(func() {
file_proto_email_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_email_proto_rawDescData)
})
return file_proto_email_proto_rawDescData
}
var file_proto_email_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proto_email_proto_goTypes = []interface{}{
(*SendRequest)(nil), // 0: email.SendRequest
(*SendResponse)(nil), // 1: email.SendResponse
}
var file_proto_email_proto_depIdxs = []int32{
0, // 0: email.Email.Send:input_type -> email.SendRequest
1, // 1: email.Email.Send:output_type -> email.SendResponse
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proto_email_proto_init() }
func file_proto_email_proto_init() {
if File_proto_email_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_proto_email_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SendRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_proto_email_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SendResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_proto_email_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_email_proto_goTypes,
DependencyIndexes: file_proto_email_proto_depIdxs,
MessageInfos: file_proto_email_proto_msgTypes,
}.Build()
File_proto_email_proto = out.File
file_proto_email_proto_rawDesc = nil
file_proto_email_proto_goTypes = nil
file_proto_email_proto_depIdxs = nil
}

View File

@@ -0,0 +1,93 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: proto/email.proto
package email
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
import (
context "context"
api "github.com/micro/micro/v3/service/api"
client "github.com/micro/micro/v3/service/client"
server "github.com/micro/micro/v3/service/server"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// Reference imports to suppress errors if they are not otherwise used.
var _ api.Endpoint
var _ context.Context
var _ client.Option
var _ server.Option
// Api Endpoints for Email service
func NewEmailEndpoints() []*api.Endpoint {
return []*api.Endpoint{}
}
// Client API for Email service
type EmailService interface {
Send(ctx context.Context, in *SendRequest, opts ...client.CallOption) (*SendResponse, error)
}
type emailService struct {
c client.Client
name string
}
func NewEmailService(name string, c client.Client) EmailService {
return &emailService{
c: c,
name: name,
}
}
func (c *emailService) Send(ctx context.Context, in *SendRequest, opts ...client.CallOption) (*SendResponse, error) {
req := c.c.NewRequest(c.name, "Email.Send", in)
out := new(SendResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Email service
type EmailHandler interface {
Send(context.Context, *SendRequest, *SendResponse) error
}
func RegisterEmailHandler(s server.Server, hdlr EmailHandler, opts ...server.HandlerOption) error {
type email interface {
Send(ctx context.Context, in *SendRequest, out *SendResponse) error
}
type Email struct {
email
}
h := &emailHandler{hdlr}
return s.Handle(s.NewHandler(&Email{h}, opts...))
}
type emailHandler struct {
EmailHandler
}
func (h *emailHandler) Send(ctx context.Context, in *SendRequest, out *SendResponse) error {
return h.EmailHandler.Send(ctx, in, out)
}

27
email/proto/email.proto Normal file
View File

@@ -0,0 +1,27 @@
syntax = "proto3";
package email;
option go_package = "./proto;email";
service Email {
rpc Send(SendRequest) returns (SendResponse) {}
}
// Send an email by passing in from, to, subject and a text or html body
message SendRequest {
// the name of the sender, can be email or name
string from = 1;
// the email address of the recipient
string to = 2;
// the email subject
string subject = 3;
// the text body
string text_body = 4;
// the html body
string html_body = 5;
}
message SendResponse {
}

8
email/publicapi.json Normal file
View File

@@ -0,0 +1,8 @@
{
"name": "email",
"icon": "✉️",
"category": "communication",
"pricing": {
"Email.Send": 1000
}
}