// SetMandrill sets the Mandrill API for sending emails. This function is not // recursive and returns nil. @todo func SetMandrill(opts ...MandrillOptions) DaemonOption { return func(da *Daemon) DaemonOption { // this whole func is just a quick write down. no idea if it's working // and refactor ... 8-) apiKey := da.Config.GetString(config.ScopeStore(da.ScopeID), config.Path(PathSmtpMandrillAPIKey)) if apiKey == "" { da.lastErrs = append(da.lastErrs, errors.New("Mandrill API Key is empty.")) return nil } md, err := gochimp.NewMandrill(apiKey) if err != nil { da.lastErrs = append(da.lastErrs, err) return nil } for _, o := range opts { o(md) } da.sendFunc = func(from string, to []string, msg io.WriterTo) error { // @todo figure out if "to" contains To, CC and BCC addresses. addr, err := mail.ParseAddress(from) if err != nil { return log.Error("mail.daemon.Mandrill.ParseAddress", "err", err, "from", from, "to", to) } r := gochimp.Recipient{ Name: addr.Name, Email: addr.Address, } var buf bytes.Buffer if _, err := msg.WriteTo(&buf); err != nil { return log.Error("mail.daemon.Mandrill.MessageWriteTo", "err", err, "from", from, "to", to, "msg", buf.String()) } resp, err := md.MessageSendRaw(buf.String(), to, r, false) if err != nil { return log.Error("mail.daemon.Mandrill.MessageSendRaw", "err", err, "from", from, "to", to, "msg", buf.String()) } if log.IsDebug() { log.Debug("mail.daemon.Mandrill.MessageSendRaw", "resp", resp, "from", from, "to", to, "msg", buf.String()) } // The last arg in MessageSendRaw means async in the Mandrill API: // Async: enable a background sending mode that is optimized for bulk sending. // In async mode, messages/send will immediately return a status of "queued" // for every recipient. To handle rejections when sending in async mode, set // up a webhook for the 'reject' event. Defaults to false for messages with // no more than 10 recipients; messages with more than 10 recipients are // always sent asynchronously, regardless of the value of async. return nil } da.dialer = nil return nil } }
// emailVendors sends an inventory email to each vendor. // This should probably be defined on vendors itself func emailVendors(v vendors) error { tmpl, err := template.New("inventoryTable").Parse(tableTmpl) if err != nil { return err } // NewMandrill never actually returns an error. mandrill, _ := gochimp.NewMandrill(*key) // Check connection to mandrill _, err = mandrill.Ping() if err != nil { return errors.New("Failed to initialize mandrill. Bad Key?") } // Convenience function for sending vendor emails send := func(to string, name string, body string) ([]gochimp.SendResponse, error) { message := gochimp.Message{} message.AddRecipients(gochimp.Recipient{to, name}) message.FromEmail = *fromEmail message.FromName = *fromName message.Subject = "Jonesborough Farmers Market Inventory Report for " + name message.Html = body return mandrill.MessageSend(message, false) } // email each vendor for _, aVendor := range v { // Skip vendors that don't have emails if aVendor.Email == "" { log.Println("No email found for " + aVendor.Name + ". Skipping...") continue } // Generate a table of items and quantities // for the vendor var t bytes.Buffer err = tmpl.Execute(&t, aVendor) if err != nil { return err } // Send the email _, err = send(aVendor.Email, aVendor.Name, t.String()) if err != nil { // Perhaps just log the error instead of dying? return err } log.Println("Email sent to " + aVendor.Name + " (" + aVendor.Email + ")") } return nil }
func newSMTP(api string, sendLimiter *rerate.Limiter, spamLimiter *rerate.Limiter) (*smtpd.Server, error) { mandrillAPI, err := gochimp.NewMandrill(api) if err != nil { return &smtpd.Server{}, err } mailHandler := makeMailHandler(mandrillAPI, sendLimiter, spamLimiter) heloChecker := makeHeloChecker(sendLimiter, spamLimiter) return &smtpd.Server{ WelcomeMessage: "Heimdall SMTP Server", Handler: mailHandler, HeloChecker: heloChecker, }, nil }
// Send Email Verification func SendVerificationEmail(user *models.User, baseURL string) error { // Open New Mandrill API api, err := gochimp.NewMandrill(MandrillAPIKey) if err != nil { return err } // Create the message message := gochimp.Message{ To: []gochimp.Recipient{ // Only One Recipient! gochimp.Recipient{ Email: user.Email, Name: user.FullName, }, }, TrackOpens: true, TrackClicks: true, InlineCss: true, AutoText: true, TrackingDomain: "track.list.hunterleath.com", SigningDomain: "list.hunterleath.com", ReturnPathDomain: "track.list.hunterleath.com", Merge: true, GlobalMergeVars: []gochimp.Var{ gochimp.Var{ Name: "NAME", Content: user.FullName, }, gochimp.Var{ Name: "LDATE", Content: time.Now().Format("Monday, January 2"), }, gochimp.Var{ Name: "VERIFICATION_URL", Content: fmt.Sprintf("%v/verify/%v/%v", baseURL, user.VerificationKey, url.QueryEscape(user.Email)), }, }, } // Send the message response, err := api.MessageSendTemplate("leath-s-list-email-verification", nil, message, false) for _, v := range response { if v.RejectedReason != "" { return errors.New(v.RejectedReason) } } return err }
func init() { rand.Seed(time.Now().UTC().UnixNano()) stripeSecretKey := config.StripeTestSecretKey stripePublicKey = config.StripeTestPublicKey var cwd, _ = filepath.Abs(filepath.Dir(os.Args[0])) if os.Getenv("ENV") == "production" { STATIC_DIR = cwd + "/" + STATIC_DIR stripeSecretKey = config.StripeLiveSecretKey stripePublicKey = config.StripeLivePublicKey } stripe.SetKey(stripeSecretKey) chimp = gochimp.NewChimp(config.MailchimpKey, true) mandrill, _ = gochimp.NewMandrill(config.MandrillKey) }
func main() { apiKey := os.Getenv("MANDRILL_KEY") mandrillApi, err := gochimp.NewMandrill(apiKey) if err != nil { fmt.Println("Error instantiating client") } templateName := "welcome email" contentVar := gochimp.Var{"main", "<h1>Welcome aboard!</h1>"} content := []gochimp.Var{contentVar} _, err = mandrillApi.TemplateAdd(templateName, fmt.Sprintf("%s", contentVar.Content), true) if err != nil { fmt.Println("Error adding template: %v", err) return } defer mandrillApi.TemplateDelete(templateName) renderedTemplate, err := mandrillApi.TemplateRender(templateName, content, nil) if err != nil { fmt.Println("Error rendering template: %v", err) return } recipients := []gochimp.Recipient{ gochimp.Recipient{Email: "*****@*****.**"}, } message := gochimp.Message{ Html: renderedTemplate, Subject: "Welcome aboard!", FromEmail: "*****@*****.**", FromName: "Boss Man", To: recipients, } _, err = mandrillApi.MessageSend(message, false) if err != nil { fmt.Println("Error sending message") } }
func main() { apiKey := os.Getenv("MANDRILL_KEY") mandrillApi, err := gochimp.NewMandrill(apiKey) if err != nil { fmt.Println("Error instantiating client") } templateName := "welcome email" contentVar := gochimp.Var{"main", "<h1>Welcome aboard!</h1>"} content := []gochimp.Var{contentVar} renderedTemplate, err := mandrillApi.TemplateRender(templateName, content, nil) if err != nil { fmt.Println("Error rendering template") } recipients := []gochimp.Recipient{ gochimp.Recipient{Email: "*****@*****.**"}, } message := gochimp.Message{ Html: renderedTemplate, Subject: "Welcome aboard!", FromEmail: "*****@*****.**", FromName: "Boss Man", To: recipients, } _, err = mandrillApi.MessageSend(message, false) if err != nil { fmt.Println("Error sending message") } }
func main() { var firstName string var lastName string var confirmationNumber string var email string url := "http://mobile.southwest.com/middleware/MWServlet" flag.StringVar(&firstName, "firstName", "", "First name for check in") flag.StringVar(&lastName, "lastName", "", "Last name for check in") flag.StringVar(&confirmationNumber, "confirmationNumber", "", "Confirmation Number for check in") flag.StringVar(&email, "email", "", "Email address to receive notifications") flag.Parse() if firstName == "" || lastName == "" || confirmationNumber == "" { log.Panic("Please ensure first name, last name and confirmation number are filled out") os.Exit(1) } s := NewSouthwest(firstName, lastName, confirmationNumber, url) resp, err := s.CheckIn() if err != nil { log.Panic(err) os.Exit(1) } if email != "" { apiKey := os.Getenv("MANDRILL_KEY") mandrillApi, err := gochimp.NewMandrill(apiKey) if err != nil { fmt.Println("Error instantiating client") } templateName := "notification" content := []gochimp.Var{ gochimp.Var{"header", "<h1>Howdy and welcome!</h1>"}, gochimp.Var{"main", fmt.Sprintf("<div>%s</div>", resp.Errmsg)}, } renderedTemplate, err := mandrillApi.TemplateRender(templateName, content, nil) if err != nil { fmt.Println(err) fmt.Println("Error rendering template") } recipients := []gochimp.Recipient{ gochimp.Recipient{Email: email}, } message := gochimp.Message{ Html: renderedTemplate, Subject: "All Set!", FromEmail: "*****@*****.**", FromName: "Checkin Agent", To: recipients, } _, err = mandrillApi.MessageSend(message, false) if err != nil { fmt.Println("Error sending message") } } log.Println(resp.Errmsg) }
func main() { flag.BoolVar(&prod, "o", false, ":sync the MailChimp templates to the official account of Mandrill.") flag.Parse() start := time.Now() var config Config content, err := ioutil.ReadFile("config.json") if err != nil { panic(err) } if err = json.Unmarshal(content, &config); err != nil { panic(err) } fmt.Println(config) return key := config.MailChimp.APIKey if key == "" { log.Println("Please specify PROD_MAILCHIMP_KEY") os.Exit(1) } mailchimp := gochimp.NewChimp(key, true) var accounts []account if prod { log.Println("Updating Production Templates") accounts = append(accounts, config.Official) } else { log.Println("Updating Dev/Test Templates") accounts = config.Accounts } slugs := config.Slugs chimpList, err := mailchimp.TemplatesList(gochimp.TemplatesList{ Types: gochimp.TemplateListType{User: true, Gallery: true, Base: true}, Filters: gochimp.TemplateListFilter{IncludeDragAndDrop: true}, }) if err != nil { panic(err) } for _, tmpl := range chimpList.User { slug, ok := slugs[tmpl.Name] if !ok { continue } log.Println("Slug:", slug) info, err := mailchimp.TemplatesInfo(gochimp.TemplateInfo{ TemplateID: tmpl.Id, Type: "user", }) if err != nil { panic(err) } for _, account := range accounts { log.Println("Account:", account.Email) mandril, err := gochimp.NewMandrill(account.APIKey) if err != nil { panic(err) } var exists bool _, err = mandril.TemplateInfo(slug) if err != nil { if merr, ok := err.(gochimp.MandrillError); !ok && merr.Name != "Unknown_Template" { panic(err) } } else { exists = true } if exists { log.Println("Action: Update") _, err = mandril.TemplateUpdate(slug, info.Source, true) } else { log.Println("Action: Add") _, err = mandril.TemplateAdd(slug, info.Source, true) } if err != nil { panic(err) } } } log.Println("Took", time.Now().Sub(start)) }