package email import ( "context" "encoding/base64" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ses" "github.com/mailgun/mailgun-go/v4" log "github.com/rs/zerolog/log" "os" "time" ) const ( //Mailgun // You can find the Private API Key in your Account Menu, under "Settings": // (https://app.mailgun.com/app/account/security) privateAPIKey = "b9e1cf13cb439a04bbe835253524e88c-4879ff27-57cad600" // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. Sender = "creditfaircapital@creditfair.in" // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. Recipient = "creditfaircapital@creditfair.in" //os.Getenv("CFC_EMAIL_GROUP_TO") CCRecipient = "maria@creditfair.in" //os.Getenv("CFC_EMAIL_GROUP_CC") // Specify a configuration set. To use a configuration // set, comment the next line and line 92. //ConfigurationSet = "ConfigSet" // The subject line for the email. //Subject = "You request for investment is under process" // The HTML body for the email. //The email body for recipients with non-HTML email clients. TextBody = "You request for investment is under process" // The character encoding for the email. CharSet = "UTF-8" ) func EmailSES(message string, Subject string) (string, error) { sender := os.Getenv("CFC_EMAIL_GROUP_FROM") CCRecipient := os.Getenv("CFC_EMAIL_GROUP_CC") Recipient := os.Getenv("CFC_EMAIL_GROUP_TO") aws_access_key_id := os.Getenv("AWS_SES_KEY_ID") //os.Getenv("AWS_ACCESS_KEY_ID") aws_secret_access_key := os.Getenv("AWS_SECRET_SES_KEY") //os.Getenv("AWS_SECRET_ACCESS_KEY") creds := credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, "") _, err := creds.Get() if err != nil { log.Print("err.Error()") log.Error().Err(err).Msg(err.Error()) return err.Error(), err } cfg := aws.NewConfig().WithRegion("ap-south-1").WithCredentials(creds) //os.Getenv("AWS_DEFAULT_REGION") // sess, err := session.NewSession(&aws.Config{ // Region:aws.String("ap-south-1")}, // ) // Create an SES session. svc := ses.New(session.New(), cfg) // Assemble the email. input := &ses.SendEmailInput{ Destination: &ses.Destination{ CcAddresses: []*string{ aws.String(CCRecipient), }, ToAddresses: []*string{ aws.String(Recipient), }, }, Message: &ses.Message{ Body: &ses.Body{ Html: &ses.Content{ Charset: aws.String(CharSet), Data: aws.String(message), }, Text: &ses.Content{ Charset: aws.String(CharSet), Data: aws.String(TextBody), }, }, Subject: &ses.Content{ Charset: aws.String(CharSet), Data: aws.String(Subject), }, }, Source: aws.String(sender), // Uncomment to use a configuration set //ConfigurationSetName: aws.String(ConfigurationSet), } // Attempt to send the email. result, err := svc.SendEmail(input) // Display error messages if they occur. if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case ses.ErrCodeMessageRejected: log.Print(ses.ErrCodeMessageRejected, aerr.Error()) case ses.ErrCodeMailFromDomainNotVerifiedException: log.Print(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) case ses.ErrCodeConfigurationSetDoesNotExistException: log.Print(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) default: log.Print(aerr.Error()) } } else { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. log.Error().Err(err).Msg(err.Error()) } return "", nil } log.Print("Email Sent to address: " + Recipient) log.Print(result) return "", nil } func EmailAttachmentSES(email string, message string, subject string, attachment map[string]string) (string, error) { log.Print(attachment) sender := os.Getenv("CFC_EMAIL_GROUP_FROM") CCRecipient := os.Getenv("CFC_EMAIL_GROUP_CC") Recipient := email //os.Getenv("CFC_EMAIL_GROUP_TO") aws_access_key_id := os.Getenv("AWS_SES_KEY_ID") //os.Getenv("AWS_ACCESS_KEY_ID") aws_secret_access_key := os.Getenv("AWS_SECRET_SES_KEY") //os.Getenv("AWS_SECRET_ACCESS_KEY") creds := credentials.NewStaticCredentials(aws_access_key_id, aws_secret_access_key, "") _, err := creds.Get() if err != nil { log.Print("err.Error()") log.Error().Err(err).Msg(err.Error()) return err.Error(), err } cfg := aws.NewConfig().WithRegion("ap-south-1").WithCredentials(creds) //os.Getenv("AWS_DEFAULT_REGION") // sess, err := session.NewSession(&aws.Config{ // Region:aws.String("ap-south-1")}, // ) // Create an SES session. svc := ses.New(session.New(), cfg) //str := base64.StdEncoding.EncodeToString([]byte(message)) var ses_mail = "From: 'Credit Fair Capital' <" + sender + ">\n" ses_mail += "To: " + Recipient + "\n" ses_mail += "Subject: " + subject + "\n" ses_mail += "MIME-Version: 1.0\n" ses_mail += "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n" ses_mail += "--NextPart\n" ses_mail += "Content-Type: text/html\n\n" ses_mail += message + ".\n\n" ses_mail += "--NextPart\n" ses_mail += "Content-Type: application/octet-stream; name=\"" + attachment["FileName"] + "\"\n" ses_mail += "Content-Transfer-Encoding: base64\n" ses_mail += "Content-Disposition: attachment\n\n" ses_mail += attachment["File"] + "\n\n" ses_mail += "--NextPart--" // Assemble the email. input := &ses.SendRawEmailInput{ Destinations: []*string{ aws.String(Recipient), // Required aws.String(CCRecipient), //aws.String(CCRecipient), // More values... }, RawMessage: &ses.RawMessage{ // Required Data: []byte(ses_mail), // Required }, Source: aws.String(sender), // Uncomment to use a configuration set //ConfigurationSetName: aws.String(ConfigurationSet), } // Attempt to send the email. result, err := svc.SendRawEmail(input) // Display error messages if they occur. if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case ses.ErrCodeMessageRejected: log.Print(ses.ErrCodeMessageRejected, aerr.Error()) case ses.ErrCodeMailFromDomainNotVerifiedException: log.Print(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) case ses.ErrCodeConfigurationSetDoesNotExistException: log.Print(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) default: log.Print(aerr.Error()) } } else { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. log.Error().Err(err).Msg(err.Error()) } return "", nil } log.Print("Email Sent to address: " + Recipient) log.Print(result) return "", nil } func Email(body string, subject string, email string, cc string) (string, error) { sender := os.Getenv("CFC_EMAIL_GROUP_FROM") sender = "info@creditfaircapital.in" RecipientEmail := os.Getenv("CFC_EMAIL_GROUP_TO") if len(email) > 0 { RecipientEmail = email } // Create an instance of the Mailgun Client mg := mailgun.NewMailgun("email.creditfair.in", privateAPIKey) //When you have an EU-domain, you must specify the endpoint: //mg.SetAPIBase("https://api.eu.mailgun.net/v3") // The message object allows you to add attachments and Bcc recipients message := mg.NewMessage(sender, subject, "", RecipientEmail) if len(cc) > 0 { message.AddCC(cc) } message.SetHtml(body) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Send the message with a 10 second timeout resp, id, err := mg.Send(ctx, message) if err != nil { log.Error().Err(err).Msg(err.Error()) return "", err } fmt.Printf("ID: %s Resp: %s\n", id, resp) return "", nil } func EmailAttachment(email string, body string, subject string, attachment map[string]string, cc string) (string, error) { sender := "info@creditfaircapital.in" //os.Getenv("CFC_EMAIL_GROUP_FROM") Recipient := email //os.Getenv("CFC_EMAIL_GROUP_TO") // Create an instance of the Mailgun Client mg := mailgun.NewMailgun("email.creditfair.in", privateAPIKey) //When you have an EU-domain, you must specify the endpoint: //mg.SetAPIBase("https://api.eu.mailgun.net/v3") // The message object allows you to add attachments and Bcc recipients message := mg.NewMessage(sender, subject, "", Recipient) if len(cc) > 0 { message.AddCC(cc) message.AddCC("info@creditfaircapital.in") } message.SetHtml(body) //file := base64ToFile(attachment) sDecFile, _ := base64.StdEncoding.DecodeString(attachment["File"]) message.AddBufferAttachment(attachment["FileName"], sDecFile) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Send the message with a 10 second timeout resp, id, err := mg.Send(ctx, message) if err != nil { log.Error().Err(err).Msg(err.Error()) return "", err } fmt.Printf("ID: %s Resp: %s\n", id, resp) return "", nil } func base64ToFile(attachment map[string]string) string { dec, err := base64.StdEncoding.DecodeString(attachment["File"]) if err != nil { panic(err) } f, err := os.Create(attachment["FileName"]) if err != nil { panic(err) } defer f.Close() if _, err := f.Write(dec); err != nil { log.Print(err.Error()) } if err := f.Sync(); err != nil { log.Print(err.Error()) } return attachment["FileName"] }