From eb0165f4bfd681aabe4af7de2f1552c7f1b33de2 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Thu, 1 Jul 2021 12:37:12 +0100 Subject: [PATCH] add an email service --- email/.gitignore | 2 + email/Dockerfile | 3 + email/Makefile | 22 +++ email/README.md | 8 ++ email/generate.go | 3 + email/handler/email.go | 130 ++++++++++++++++++ email/main.go | 27 ++++ email/proto/email.pb.go | 244 ++++++++++++++++++++++++++++++++++ email/proto/email.pb.micro.go | 93 +++++++++++++ email/proto/email.proto | 27 ++++ email/publicapi.json | 8 ++ 11 files changed, 567 insertions(+) create mode 100644 email/.gitignore create mode 100644 email/Dockerfile create mode 100644 email/Makefile create mode 100644 email/README.md create mode 100644 email/generate.go create mode 100644 email/handler/email.go create mode 100644 email/main.go create mode 100644 email/proto/email.pb.go create mode 100644 email/proto/email.pb.micro.go create mode 100644 email/proto/email.proto create mode 100644 email/publicapi.json diff --git a/email/.gitignore b/email/.gitignore new file mode 100644 index 0000000..9536269 --- /dev/null +++ b/email/.gitignore @@ -0,0 +1,2 @@ + +emails diff --git a/email/Dockerfile b/email/Dockerfile new file mode 100644 index 0000000..f3bb29f --- /dev/null +++ b/email/Dockerfile @@ -0,0 +1,3 @@ +FROM alpine +ADD email /email +ENTRYPOINT [ "/email" ] diff --git a/email/Makefile b/email/Makefile new file mode 100644 index 0000000..7b2c4c1 --- /dev/null +++ b/email/Makefile @@ -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 diff --git a/email/README.md b/email/README.md new file mode 100644 index 0000000..8351b5e --- /dev/null +++ b/email/README.md @@ -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) + diff --git a/email/generate.go b/email/generate.go new file mode 100644 index 0000000..7d9db91 --- /dev/null +++ b/email/generate.go @@ -0,0 +1,3 @@ +package main + +//go:generate make proto diff --git a/email/handler/email.go b/email/handler/email.go new file mode 100644 index 0000000..160cb82 --- /dev/null +++ b/email/handler/email.go @@ -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 +} diff --git a/email/main.go b/email/main.go new file mode 100644 index 0000000..f0bae54 --- /dev/null +++ b/email/main.go @@ -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) + } +} diff --git a/email/proto/email.pb.go b/email/proto/email.pb.go new file mode 100644 index 0000000..3039b9d --- /dev/null +++ b/email/proto/email.pb.go @@ -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 +} diff --git a/email/proto/email.pb.micro.go b/email/proto/email.pb.micro.go new file mode 100644 index 0000000..e4c7930 --- /dev/null +++ b/email/proto/email.pb.micro.go @@ -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) +} diff --git a/email/proto/email.proto b/email/proto/email.proto new file mode 100644 index 0000000..d5123ad --- /dev/null +++ b/email/proto/email.proto @@ -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 { +} + diff --git a/email/publicapi.json b/email/publicapi.json new file mode 100644 index 0000000..95aacbf --- /dev/null +++ b/email/publicapi.json @@ -0,0 +1,8 @@ +{ + "name": "email", + "icon": "✉️", + "category": "communication", + "pricing": { + "Email.Send": 1000 + } +}