func TestGetStoredMessage(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") id, err := findStoredMessageID(mg) // somehow... if err != nil { t.Fatal(err) } // First, get our stored message. msg, err := mg.GetStoredMessage(id) if err != nil { t.Fatal(err) } fields := map[string]string{ " From": msg.From, " Sender": msg.Sender, " Subject": msg.Subject, "Attachments": fmt.Sprintf("%d", len(msg.Attachments)), " Headers": fmt.Sprintf("%d", len(msg.MessageHeaders)), } for k, v := range fields { fmt.Printf("%13s: %s\n", k, v) } // We're done with it; now delete it. err = mg.DeleteStoredMessage(id) if err != nil { t.Fatal(err) } }
func RunApplication() { config := CreateConfigFromEnv() PrintConfig(config) mg := mailgun.NewMailgun(config.Domain, config.ApiKey, "") StartHttpServer(mg, config) }
func TestDeleteTag(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") err := mg.DeleteTag("newsletter") if err != nil { t.Fatal(err) } }
func TestSendMGMIME(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") m := mg.NewMIMEMessage(ioutil.NopCloser(strings.NewReader(exampleMime)), toUser) msg, id, err := mg.Send(m) if err != nil { t.Fatal(err) } fmt.Println("TestSendMIME:MSG(" + msg + "),ID(" + id + ")") }
func TestSendLegacyPlain(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") publicApiKey := reqEnv(t, "MG_PUBLIC_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, publicApiKey) m := mailgun.NewMessage(fromUser, exampleSubject, exampleText, toUser) msg, id, err := mg.Send(m) if err != nil { t.Fatal(err) } fmt.Println("TestSendPlain:MSG(" + msg + "),ID(" + id + ")") }
func TestSendMGPlainAt(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") publicApiKey := reqEnv(t, "MG_PUBLIC_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, publicApiKey) m := mg.NewMessage(fromUser, exampleSubject, exampleText, toUser) m.SetDeliveryTime(time.Now().Add(5 * time.Minute)) msg, id, err := mg.Send(m) if err != nil { t.Fatal(err) } fmt.Println("TestSendPlainAt:MSG(" + msg + "),ID(" + id + ")") }
func TestGetBounces(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") n, bounces, err := mg.GetBounces(-1, -1) if err != nil { t.Fatal(err) } if n > 0 { t.Fatal("Expected no bounces for what should be a clean domain.") } if n != len(bounces) { t.Fatalf("Expected length of bounces %d to equal returned length %d", len(bounces), n) } }
func (cfg MailgunEmailerConfig) Emailer(fromAddr string) (Emailer, error) { from := cfg.FromAddr if from == "" { from = fromAddr } if from == "" { return nil, errors.New(`missing "from" field in email config`) } mg := mailgun.NewMailgun(cfg.Domain, cfg.PrivateAPIKey, cfg.PublicAPIKey) return &mailgunEmailer{ mg: mg, from: from, }, nil }
// sendWithMailgun handles the main send and logging logic for any single email deploy func (c *Client) sendWithMailgun() (string, error) { var err error c.Body, err = c.prepareTmpl() if err != nil { return "", err } gun := mg.NewMailgun(Conf["mailgun"]["domain"], Conf["mailgun"]["secret"], Conf["mailgun"]["public"]) // override the http client client := urlfetch.Client(c.context) gun.SetClient(client) // generate mailgun message message := mg.NewMessage(fmt.Sprintf("%s <%s>", Conf["default"]["fromname"], Conf["default"]["fromemail"]), c.Subject, c.Body, c.Recipient[0].Render) message.SetHtml(strings.Replace(c.Body, "\\", "", -1)) // add additional recipients for k, v := range c.Recipient { if k > 0 { err := message.AddRecipient(v.Render) if err != nil { c.context.Errorf("Could not append [%s] as Mailgun recipient: %v", v.Render, err) return "", err } } } // send the email _, id, err := gun.Send(message) if err != nil { c.context.Errorf("Error: %v", err) return "", err } if Conf["default"]["logmessages"] == "true" { // if the id is not empty then add to the message log if id != "" { _, logErr := c.addMessageLog() if logErr != nil { c.context.Errorf("Failed to add message to log: %v", logErr) } } } return id, err }
func NotifyUser(name, email, subject, message string) { fmt.Printf("Notifying %s with subject:\n", email) fmt.Printf("%s\n", subject) mailto := fmt.Sprintf("%s <%s>", name, email) gun := mailgun.NewMailgun("mail.ckpt.no", os.Getenv("CKPT_MAILGUN_KEY"), "pubkey-b3e133632123a0da24d1e2c5842039b6") m := mailgun.NewMessage("CKPT <*****@*****.**>", subject, message, mailto) m.AddHeader("Content-Type", "text/plain; charset=\"utf-8\"") response, id, err := gun.Send(m) if err != nil { fmt.Printf("Error:\n%+v\n", err.Error()) } fmt.Printf("Response ID: %s\n", id) fmt.Printf("Message from server: %s\n", response) }
func TestSendMGBatchFailRecipients(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") m := mg.NewMessage(fromUser, exampleSubject, exampleText+"Batch\n") for i := 0; i < mailgun.MaxNumberOfRecipients; i++ { m.AddRecipient("") // We expect this to indicate a failure at the API } err := m.AddRecipientAndVariables(toUser, nil) if err == nil { // If we're here, either the SDK didn't send the message, // OR the API didn't check for empty To: headers. t.Fatal("Expected to fail!!") } }
func TestSendMGTag(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") publicApiKey := reqEnv(t, "MG_PUBLIC_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, publicApiKey) m := mg.NewMessage(fromUser, exampleSubject, exampleText+"Tags Galore!\n", toUser) m.AddTag("FooTag") m.AddTag("BarTag") m.AddTag("BlortTag") msg, id, err := mg.Send(m) if err != nil { t.Fatal(err) } fmt.Println("TestSendTag:MSG(" + msg + "),ID(" + id + ")") }
func TestGetCredentials(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") n, cs, err := mg.GetCredentials(mailgun.DefaultLimit, mailgun.DefaultSkip) if err != nil { t.Fatal(err) } tw := &tabwriter.Writer{} tw.Init(os.Stdout, 2, 8, 2, ' ', 0) fmt.Fprintf(tw, "Login\tCreated At\t\n") for _, c := range cs { fmt.Fprintf(tw, "%s\t%s\t\n", c.Login, c.CreatedAt) } tw.Flush() fmt.Printf("%d credentials listed out of %d\n", len(cs), n) }
func setup(t *testing.T) (mailgun.Mailgun, string) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") address := fmt.Sprintf("list5@%s", domain) _, err := mg.CreateList(mailgun.List{ Address: address, Name: address, Description: "TestMailingListMembers-related mailing list", AccessLevel: mailgun.Members, }) if err != nil { t.Fatal(err) } return mg, address }
func TestGetSingleBounce(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") exampleEmail := fmt.Sprintf("baz@%s", domain) _, err := mg.GetSingleBounce(exampleEmail) if err == nil { t.Fatal("Did not expect a bounce to exist") } ure, ok := err.(*mailgun.UnexpectedResponseError) if !ok { t.Fatal("Expected UnexpectedResponseError") } if ure.Actual != 404 { t.Fatalf("Expected 404 response code; got %d", ure.Actual) } }
func TestSendMGBatchRecipientVariables(t *testing.T) { toUser := reqEnv(t, "MG_EMAIL_TO") domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") m := mg.NewMessage(fromUser, exampleSubject, templateText) err := m.AddRecipientAndVariables(toUser, map[string]interface{}{ "name": "Joe Cool Example", "table": 42, }) if err != nil { t.Fatal(err) } _, _, err = mg.Send(m) if err != nil { t.Fatal(err) } }
func TestGetStats(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") totalCount, stats, err := mg.GetStats(-1, -1, nil, "sent", "opened") if err != nil { t.Fatal(err) } fmt.Printf("Total Count: %d\n", totalCount) tw := tabwriter.NewWriter(os.Stdout, 2, 8, 2, ' ', tabwriter.AlignRight) fmt.Fprintf(tw, "Id\tEvent\tCreatedAt\tTotalCount\t\n") for _, stat := range stats { fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t\n", stat.Id, stat.Event, stat.CreatedAt, stat.TotalCount) } tw.Flush() }
func TestCreateDestroyUnsubscription(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") email := reqEnv(t, "MG_EMAIL_ADDR") mg := mailgun.NewMailgun(domain, apiKey, "") // Create unsubscription record err := mg.Unsubscribe(email, "*") if err != nil { t.Fatal(err) } // Destroy the unsubscription record err = mg.RemoveUnsubscribe(email) if err != nil { t.Fatal(err) } }
func TestGetUnsubscribes(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") n, us, err := mg.GetUnsubscribes(mailgun.DefaultLimit, mailgun.DefaultSkip) if err != nil { t.Fatal(err) } fmt.Printf("Received %d out of %d unsubscribe records.\n", len(us), n) if len(us) > 0 { tw := &tabwriter.Writer{} tw.Init(os.Stdout, 2, 8, 2, ' ', 0) fmt.Fprintln(tw, "ID\tAddress\tCreated At\tTag\t") for _, u := range us { fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t\n", u.ID, u.Address, u.CreatedAt, u.Tag) } tw.Flush() } }
func (m *mailgunner) Send(msg string, sender string, subject string, to string) error { if len(strings.TrimSpace(sender)) <= 0 { sender = "Kishore CEO <*****@*****.**>" } mg := mailgun.NewMailgun(m.domain, m.api_key, "") g := mailgun.NewMessage( sender, subject, "You are in !", to, ) g.SetHtml(msg) g.SetTracking(true) _, id, err := mg.Send(g) if err != nil { return err } log.Infof("Mailgun sent %s", id) return nil }
func (m *mailgunner) Send(msg string, sender string, subject string, to string) error { if len(strings.TrimSpace(sender)) <= 0 { sender = m.sender } mg := mailgun.NewMailgun(m.domain, m.api_key, "") g := mailgun.NewMessage( sender, subject, "You are in !", to, ) g.SetHtml(msg) g.SetTracking(false) //g.SetTrackingClicks(false) //g.SetTrackingOpens(false) _, id, err := mg.Send(g) if err != nil { return err } log.Infof("Mailgun sent %s", id) return nil }
func TestCreateDeleteCredentials(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") randomPassword := randomString(16, "pw") randomID := randomString(16, "usr") randomLogin := fmt.Sprintf("%s@%s", randomID, domain) err := mg.CreateCredential(randomLogin, randomPassword) if err != nil { t.Fatal(err) } err = mg.ChangeCredentialPassword(randomID, randomString(16, "pw2")) if err != nil { t.Fatal(err) } err = mg.DeleteCredential(randomID) if err != nil { t.Fatal(err) } }
func (cfg MailgunEmailerConfig) Emailer() (Emailer, error) { mg := mailgun.NewMailgun(cfg.Domain, cfg.PrivateAPIKey, cfg.PublicAPIKey) return &mailgunEmailer{ mg: mg, }, nil }
func TestAddDelBounces(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") // Compute an e-mail address for our domain. exampleEmail := fmt.Sprintf("baz@%s", domain) // First, basic sanity check. // Fail early if we have bounces for a fictitious e-mail address. n, _, err := mg.GetBounces(-1, -1) if err != nil { t.Fatal(err) } if n > 0 { t.Fatal("Expected no bounces for what should be a clean domain.") } bounce, err := mg.GetSingleBounce(exampleEmail) if err == nil { t.Fatalf("Expected no bounces for %s", exampleEmail) } // Add the bounce for our address. err = mg.AddBounce(exampleEmail, "550", "TestAddDelBounces-generated error") if err != nil { t.Fatal(err) } // We should now have one bounce listed when we query the API. n, bounces, err := mg.GetBounces(-1, -1) if err != nil { t.Fatal(err) } if n != 1 { t.Fatal("Expected one bounce for this domain.") } if bounces[0].Address != exampleEmail { t.Fatalf("Expected bounce for address %s; got %s", exampleEmail, bounces[0].Address) } bounce, err = mg.GetSingleBounce(exampleEmail) if err != nil { t.Fatal(err) } if bounce.CreatedAt == "" { t.Fatalf("Expected at least one bounce for %s", exampleEmail) } // Delete it. This should put us back the way we were. err = mg.DeleteBounce(exampleEmail) if err != nil { t.Fatal(err) } // Make sure we're back to the way we were. n, _, err = mg.GetBounces(-1, -1) if err != nil { t.Fatal(err) } if n > 0 { t.Fatal("Expected no bounces for what should be a clean domain.") } _, err = mg.GetSingleBounce(exampleEmail) if err == nil { t.Fatalf("Expected no bounces for %s", exampleEmail) } }
func Init(mailgunDomain string, mailgunPrivateKey string, mailgunPublicKey string) { gun = mailgun.NewMailgun(mailgunDomain, mailgunPrivateKey, mailgunPublicKey) }
// "github.com/armon/go-radix" // "github.com/miekg/radix" // "github.com/manveru/trie" // "github.com/IanLewis/codekata" // exercise // Single word search: // "github.com/AlasdairF/Tokenize" // "github.com/typeflow/typeflow-go" // "github.com/blevesearch/bleve/search" // "github.com/typerandom/cleo" // "github.com/sajari/fuzzy" // "github.com/smartystreets/mafsa" "os" "runtime" ) var gun = mailgun.NewMailgun("aabenhave.dk", "key-2dcm94f8dttfm4k4xid3y8x2c8et-op6", "pubkey-3c1amkiwdizjhoa-cqnkrlvylm0pmiq4") func main() { c := runtime.NumCPU() runtime.GOMAXPROCS(c) os.Mkdir("data", 0777) e.LogInit() testRandom() test := Test{} test.Codex() } func initExp() { e.InfoLog.Println("Init various") e.InfoLog.Println(conv.String(74534537787)) test := Test{}
func TestMailingLists(t *testing.T) { domain := reqEnv(t, "MG_DOMAIN") apiKey := reqEnv(t, "MG_API_KEY") mg := mailgun.NewMailgun(domain, apiKey, "") listAddr := fmt.Sprintf("list2@%s", domain) protoList := mailgun.List{ Address: listAddr, Name: "List1", Description: "A list created by an acceptance test.", AccessLevel: mailgun.Members, } var countLists = func() int { total, _, err := mg.GetLists(mailgun.DefaultLimit, mailgun.DefaultSkip, "") if err != nil { t.Fatal(err) } return total } startCount := countLists() _, err := mg.CreateList(protoList) if err != nil { t.Fatal(err) } defer func() { err = mg.DeleteList(listAddr) if err != nil { t.Fatal(err) } newCount := countLists() if newCount != startCount { t.Fatalf("Expected %d lists defined; got %d", startCount, newCount) } }() newCount := countLists() if newCount <= startCount { t.Fatalf("Expected %d lists defined; got %d", startCount+1, newCount) } theList, err := mg.GetListByAddress(listAddr) if err != nil { t.Fatal(err) } protoList.CreatedAt = theList.CreatedAt // ignore this field when comparing. if theList != protoList { t.Fatalf("Unexpected list descriptor: Expected [%#v], Got [%#v]", protoList, theList) } _, err = mg.UpdateList(listAddr, mailgun.List{ Description: "A list whose description changed", }) if err != nil { t.Fatal(err) } theList, err = mg.GetListByAddress(listAddr) if err != nil { t.Fatal(err) } newList := protoList newList.Description = "A list whose description changed" if theList != newList { t.Fatalf("Expected [%#v], Got [%#v]", newList, theList) } }
func main() { domain := flag.String("domain", "", "mailgun domain") privateKey := flag.String("private-key", "", "secret mailgun api key") publicKey := flag.String("public-key", "", "mailgun public api key") dry := flag.Bool("dry", false, "do not update cache & only print to stdout (no e-mail)") verbose := flag.Bool("verbose", false, "Print detailed output per monitored url.") flag.Parse() if *domain == "" || *privateKey == "" || *publicKey == "" { log.Fatalln("domain, private-key and public-key flags are required") } gun := m.NewMailgun(*domain, *privateKey, *publicKey) urls := loadUrls() for _, url := range urls { body, err := requestURL(url) if err != nil { log.Println("Skipped URL because of error requesting it:", url) continue } filename := getExecFolder() + "/cache/" + getMD5Hash(url) + ".html" cached, err := ioutil.ReadFile(filename) if err != nil { if *dry == false { updateCache(filename, body) } switch err := err.(type) { case *os.PathError: fmt.Printf("This URL will now be monitored: %s\n\n", url) default: log.Fatalf("Fatal errors type %T\n", err) } } else { if reflect.DeepEqual(cached, body) { if *verbose { fmt.Printf("This URL didn't change: %s\n\n", url) } } else { cachedDoc := getGoqueryDoc(cached) currentDoc := getGoqueryDoc(body) cachedContent, _ := cachedDoc.Find("#content").Html() currentContent, _ := currentDoc.Find("#content").Html() if cachedContent == currentContent { if *verbose { fmt.Println("The website changed, but the content stayed the same.") } } else { cachedText, _ := html2text.FromString(cachedContent) currentText, _ := html2text.FromString(currentContent) diff := difflib.Diff(strings.Split(cachedText, "\n"), strings.Split(currentText, "\n")) msg := createMessage(diff, url) htmlMsg := createHTMLMessage(diff, url) if *dry { fmt.Println(msg) } else { sendEmails(gun, msg, htmlMsg) } } if *dry == false { updateCache(filename, body) } } } } }