Skip to content

Commit

Permalink
multiple recipients
Browse files Browse the repository at this point in the history
  • Loading branch information
Xinguang Wang committed Nov 19, 2019
1 parent aa6f885 commit 92b0e28
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 25 deletions.
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Contact forms. They are all around us. Almost every website has one.
* [Create Lambda function](docs/Lambda.md)
* [Create API gateway endpoint](docs/APIgateway.md)
* [Integrate Google reCAPTCHA in your website](#website)
* [Environment variables](#environment)

## Build Project <a name="build" />

Expand Down Expand Up @@ -98,4 +99,42 @@ Let’s look at the [sample code](example.html) to understand it better.

```url
"https://API_Gateway_id.execute-api.ap-northeast-1.amazonaws.com/v1/sendmail";
```
```

## Environment variables <a name="environment" />

| Key | Value |
| ------------- | ------------- |
| SENDMAIL_SUBJECT | email subject |
| SENDMAIL_MAILTYPE | html or plain |
| SENDER_USER | smtp user name |
| SENDER_NAME | the display sender name |
| SENDER_PASSWORD | smtp password |
| SENDER_HOST | smtp host(E.g., example.com) |
| SENDER_PORT | smtp port(E.g., 587) |
| RECIPIENTS | recipients (E.g., recipient <[email protected]>;recipient <[email protected]>;) |
| SECRET_KEY | reCaptcha Secret Key |


### Dev environment

- https://www.jianshu.com/p/166d272f51b3
-
```sh
sam init --runtime

sam local invoke SendmailFunction --event test-event.json
# or
sam local start-api

curl -i -X POST \
-H "content-type:application/json" \
-d \
'{
"name":"にほんご",
"email":"[email protected]",
"message":"にほんご",
"token":"tokenxxxxx"
}' \
'http://127.0.0.1:3000/sendmail'
```
21 changes: 15 additions & 6 deletions recaptcha/lambdahandle.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package recaptcha

import (
"errors"
"net/mail"

"github.com/Xinguang/lambda-sendmail/sendmail"
"github.com/aws/aws-lambda-go/events"
log "github.com/sirupsen/logrus"
)

Expand All @@ -16,11 +16,15 @@ type Contact struct {
}

// Handle for verify a user's response to a reCAPTCHA challenge
func Handle(contact Contact) (string, error) {
func Handle(contact Contact) (events.APIGatewayProxyResponse, error) {
if !verify(contact.Token) {
return "", errors.New("timeout-or-duplicate")
return events.APIGatewayProxyResponse{
Body: "timeout-or-duplicate",
StatusCode: 400,
}, nil
}

log.Info(contact)
reply := mail.Address{Name: contact.Name, Address: contact.Email}
message := sendmail.NewMessage()

Expand All @@ -32,8 +36,13 @@ func Handle(contact Contact) (string, error) {

if err != nil {
log.Fatal(err)
return "", err
return events.APIGatewayProxyResponse{
Body: "there is some errors",
StatusCode: 400,
}, err
}

return "verify", nil
return events.APIGatewayProxyResponse{
Body: contact.Message,
StatusCode: 200,
}, nil
}
6 changes: 0 additions & 6 deletions recaptcha/recaptcha.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,6 @@ type Response struct {
}

func verify(token string) bool {
// data := url.Values{
// "secret": {SECRET},
// "response": {token},
// }
// body := strings.NewReader(data.Encode())

var r http.Request
r.ParseForm()
r.Form.Add("secret", SECRET)
Expand Down
35 changes: 23 additions & 12 deletions sendmail/sendmail.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/mail"
"net/smtp"
"os"
"strings"

log "github.com/sirupsen/logrus"
)
Expand All @@ -17,30 +18,38 @@ var (
SENDER_PASSWORD = os.Getenv("SENDER_PASSWORD")
SENDER_HOST = os.Getenv("SENDER_HOST")
SENDER_PORT = os.Getenv("SENDER_PORT") // default 587
RECIPIENT = os.Getenv("RECIPIENT") // name<[email protected]>
RECIPIENTS = os.Getenv("RECIPIENTS") // <[email protected]>;recipient <[email protected]>;
)

// The recipient address
var recipient = func() *mail.Address {
address, err := mail.ParseAddress(RECIPIENT)
if err != nil {
log.Fatal(err)
var recipients = func() []*mail.Address {
addressList := []*mail.Address{}
var mailList = strings.Split(RECIPIENTS, ";")
for _, mailString := range mailList {
recipient, err := mail.ParseAddress(mailString)
if err != nil {
continue
}
addressList = append(addressList, recipient)
}
return address
return addressList
}()

func Send(msg Message) error {
// The servername must include a port, as in "mail.example.com:smtp".
servername := fmt.Sprintf("%s:%s", SENDER_HOST, SENDER_PORT)
auth := smtp.PlainAuth("", SENDER_USER, SENDER_PASSWORD, SENDER_HOST)
recipients := []string{recipient.Address}
msg.Add("To", recipient.String())
toList := []string{}
for _, recipient := range recipients {
toList = append(toList, recipient.Address)
}
msg.Add("To", strings.Join(strings.Split(RECIPIENTS, ";"), ","))
from := mail.Address{Name: SENDER_NAME, Address: SENDER_USER}
msg.Add("From", from.String())

log.Infof("recipients %s", recipient.String())
log.Infof("recipients %s", recipients)

return smtp.SendMail(servername, auth, from.Address, recipients, msg.getContent())
return smtp.SendMail(servername, auth, from.Address, toList, msg.getContent())
}

// SendMail connects to the server at addr, switches to TLS if
Expand Down Expand Up @@ -97,8 +106,10 @@ var writeCloser = func(client *smtp.Client, from string) io.WriteCloser {
if err := client.Mail(from); err != nil {
log.Fatal(err)
}
if err := client.Rcpt(recipient.Address); err != nil {
log.Fatal(err)
for _, recipient := range recipients {
if err := client.Rcpt(recipient.Address); err != nil {
log.Fatal(err)
}
}
// Data
w, err := client.Data()
Expand Down
50 changes: 50 additions & 0 deletions template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sendmail-app
Sample SAM Template for sendmail-app
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 10

Resources:
SendmailFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: ./
Handler: main
Runtime: go1.x
Tracing: Active # https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html
Events:
CatchAll:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /sendmail
Method: POST
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
RECIPIENTS: <info@site>;recipient <[email protected]>;
SENDMAIL_SUBJECT: testMail
SENDMAIL_MAILTYPE: html
SENDER_NAME: sender
SENDER_USER: [email protected]
SENDER_PASSWORD: password
SENDER_HOST: sender.com
SENDER_PORT: 587

Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldAPI:
Description: "API Gateway endpoint URL for Prod environment for First Function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "First Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
6 changes: 6 additions & 0 deletions test-event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name":"にほんご",
"email":"[email protected]",
"message":"にほんご",
"token":"にほんご"
}

0 comments on commit 92b0e28

Please sign in to comment.