func (self *MailMessage) Send() error { var auth smtp.Auth if err := self.Validate(); err != nil { return err } to := make([]string, len(self.To)) for i := range self.To { to[i] = self.To[i].Address } from := self.From.Address if from == "" { from = AppConfig.smtpUser // Config.From.Address } addr := fmt.Sprintf("%s:%d", AppConfig.smtpHost, AppConfig.smtpPort) if AppConfig.smtpTLS { auth = fakeAuth{smtp.PlainAuth("", AppConfig.smtpUser, AppConfig.smtpPassword, AppConfig.smtpHost)} } else { auth = smtp.PlainAuth("", AppConfig.smtpUser, AppConfig.smtpPassword, AppConfig.smtpHost) } return smtp.SendMail(addr, auth, from, to, []byte(self.String())) }
// Sends the content passed as parameter to the recipient list // of the given batch result func (s *SmtpConfig) sendEmailHtml(r *BatchResult, content string) { mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" subject := fmt.Sprintf("Subject: MysqlBatch Results for the batch \"%s\"\n", r.BatchName) TraceActivity.Printf("sending the email : %s \n", subject) dest := make([]string, 0) for _, d := range r.Recipients.RecipientList { dest = append(dest, d.Address) } auth := smtp.PlainAuth( "", s.User, s.Password, s.Server, ) err := smtp.SendMail( s.Server+":"+s.Port, auth, s.getSender(), dest, []byte(subject+mime+content), ) if err != nil { TraceActivity.Printf("error sending the email : %s \n", err.Error()) log.Fatal(err) } }
func getSMTPAuth(hasAuth bool, mechs string) (smtp.Auth, *tls.Config, error) { if !hasAuth { return nil, nil, nil } username := os.Getenv("SMTP_AUTH_USERNAME") for _, mech := range strings.Split(mechs, " ") { switch mech { case "CRAM-MD5": secret := os.Getenv("SMTP_AUTH_SECRET") if secret == "" { continue } return smtp.CRAMMD5Auth(username, secret), nil, nil case "PLAIN": password := os.Getenv("SMTP_AUTH_PASSWORD") if password == "" { continue } identity := os.Getenv("SMTP_AUTH_IDENTITY") // We need to know the hostname for both auth and TLS. host, _, err := net.SplitHostPort(*smtpSmartHost) if err != nil { return nil, nil, fmt.Errorf("invalid address: %s", err) } auth := smtp.PlainAuth(identity, username, password, host) cfg := &tls.Config{ServerName: host} return auth, cfg, nil } } return nil, nil, nil }
func alert(domain string, error_message string) { fmt.Println("Sending mail") subject := fmt.Sprintf("Subject: %s is down\r\n\r\n", domain) auth := smtp.PlainAuth( "", config.SMTP.Username, config.SMTP.Password, config.SMTP.Host, ) err := smtp.SendMail( config.SMTP.OutgoingServer, auth, config.SMTP.From, config.ToEmail, []byte(subject+error_message), ) if err != nil { fmt.Println(err) } else { fmt.Println("Mail sent") } }
// CreateMailer is a constructor for gsmtp.Mailer func CreateMailer(username, password, host, port string) (m *Mailer) { m = &Mailer{ auth: smtp.PlainAuth("", username, password, host), address: fmt.Sprintf("%v:%v", host, port), } return m }
// Send mail. func (mail Config) Send(to, subject, template string, args map[string]interface{}) { switch mail.Mode { case "smtp": host := mail.Config["host"] sender := mail.Config["sender"] user, useAuth := mail.Config["username"] password, _ := mail.Config["password"] var auth smtp.Auth if useAuth { auth = smtp.PlainAuth("", user, password, host) } var buf bytes.Buffer buf.WriteString("From: ") buf.WriteString(sender) buf.WriteString("\n") buf.WriteString("To: ") buf.WriteString(to) buf.WriteString("\n") buf.WriteString("Subject: ") buf.WriteString(subject) buf.WriteString("\n\n") tmpl.ExecuteTemplate(&buf, template, args) smtp.SendMail(host, auth, sender, []string{to}, bytes.Replace([]byte{'\n'}, buf.Bytes(), []byte{'\n', '\r'}, -1)) } }
func (self mailerImpl) Send(mail Mail) error { e := email.NewEmail() if mail.From != "" { e.From = mail.From } else { e.From = self.cfg.Email } e.To = mail.To e.Cc = mail.Cc e.Bcc = mail.Bcc e.Subject = mail.Subject e.HTML = []byte(mail.Body) for _, attachment := range mail.Attachments { e.AttachFile(attachment) } hostAndPort := strings.Join([]string{ self.cfg.Host, strconv.Itoa(self.cfg.Port), }, ":") plainAuth := smtp.PlainAuth( "", // identity self.cfg.Email, self.cfg.Password, self.cfg.Host, ) return e.Send(hostAndPort, plainAuth) }
// Send sends the composed email func (email *email) Send(address string) error { var auth smtp.Auth from := email.getFrom() if from == "" { return errors.New(`Mail Error: No "From" address specified.`) } if len(email.recipients) < 1 { return errors.New("Mail Error: No recipient specified.") } msg := email.GetMessage() host, port, err := net.SplitHostPort(address) if err != nil { return errors.New("Mail Error: " + err.Error()) } if email.Username != "" || email.Password != "" { auth = smtp.PlainAuth("", email.Username, email.Password, host) } return send(host, port, from, email.recipients, msg, auth, email.Encryption, email.TLSConfig, email.ConnectTimeout) }
func (this *EmailService) SendEmail(to, subject, body string) (ok bool, e string) { InitEmailFromDb() if host == "" || emailPort == "" || username == "" || password == "" { return } hp := strings.Split(host, ":") auth := smtp.PlainAuth("", username, password, hp[0]) var content_type string mailtype := "html" if mailtype == "html" { content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8" } else { content_type = "Content-Type: text/plain" + "; charset=UTF-8" } msg := []byte("To: " + to + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) send_to := strings.Split(to, ";") err := smtp.SendMail(host+":"+emailPort, auth, username, send_to, msg) if err != nil { e = fmt.Sprint(err) return } ok = true return }
func (e *Email) send(events []notices.Event) error { if e.debounce { events = e.cleanupEvents(events) } if len(events) == 0 { return nil } identity := e.params["identity"] from := e.params["from"] to := e.params["to"] password := e.params["password"] host := e.params["host"] port := e.params["port"] auth := smtp.PlainAuth(identity, from, password, host) buf := bytes.NewBuffer([]byte{}) if err := e.tmpl.Execute(buf, events); err != nil { return err } msg := buf.String() body := "From: " + from + "\r\n" body += "To: " + to + "\r\n" body += "Subject: " + e.subject(events) + "\r\n" body += "MIME-Version: 1.0\r\n" body += "Content-Type: text/plain; charset=\"utf-8\"\r\n" body += "Content-Transfer-Encoding: base64\r\n" body += base64.StdEncoding.EncodeToString([]byte(msg)) return smtp.SendMail(host+":"+port, auth, from, []string{to}, []byte(body)) }
func sendEmail(count int) { if notificationsEnabled == false { return } fmt.Println("Sending the email") subjectString := "ALERT: INVENTORY LOW" bodyString := "" if count == 0 { bodyString = "Out of items, please refill" } else if count == 1 { bodyString = "You only have 1 item left, order some moar" } else if count < 3 { bodyString = "Running low, be aware" } go sendSlackMessage(bodyString) emailUser := &EmailUser{"monitor.inventory", "squaresquaresquare1!", "smtp.gmail.com", 587} auth := smtp.PlainAuth("", emailUser.Username, emailUser.Password, emailUser.EmailServer) emailBody := fmt.Sprintf("From: AlwaysBeer\nTo: Dear Customer\nSubject: %s\n\n%s\nBottles Left: %d\n", subjectString, bodyString, count) err := smtp.SendMail(emailUser.EmailServer+":"+strconv.Itoa(emailUser.Port), auth, emailUser.Username, emailList, []byte(emailBody)) if err != nil { fmt.Println("ERROR: attempting to send a mail ", err) } }
func (fm *FeedMailer) mail(ch *rss.Channel, item *rss.Item) error { date, _ := item.ParsedPubDate() data := struct { SubjectPrefix, ChanTitle, ItemTitle string Date time.Time Links []*rss.Link Description string Content *rss.Content }{fm.prof.SubjectPrefix, ch.Title, item.Title, date, item.Links, item.Description, item.Content} msg := &bytes.Buffer{} if err := mailTemplate.Execute(msg, data); err != nil { return err } log.Printf("Sending e-mail: [%s] %s", ch.Title, item.Title) auth := smtp.PlainAuth("", fm.prof.SmtpUser, fm.prof.SmtpPass, fm.prof.SmtpHost) err := smtp.SendMail(fm.prof.SmtpAddr, auth, fm.prof.SrcEmail, fm.prof.DstEmails, msg.Bytes()) if err != nil { return err } return nil }
// Send sends the message that has been setup. func (m *Message) Send(c *Configuration) { emailUser := &GmailConf{c.Username, c.Password, c.Server, c.Port} auth := smtp.PlainAuth("", emailUser.Username, emailUser.Password, emailUser.EmailServer) var err error var doc bytes.Buffer err = smtp.SendMail(fmt.Sprintf("%s:%s", emailUser.EmailServer, strconv.Itoa(emailUser.Port)), auth, emailUser.Username, []string{"*****@*****.**"}, doc.Bytes()) if err != nil { log.Fatalln(err) } t, err := template.New("emailTemplate").Parse(emailTemplate) if err != nil { log.Fatalln("error trying to parse mail template") } err = t.Execute(&doc, m) if err != nil { log.Fatalln(err) } }
// send a message through email func sendReportMail(subject, body string) { clear() // indicate that mail is being sent fmt.Printf("Sending mail to %s...\n", RCVR_ADD) var err error // error var doc bytes.Buffer // buffer of bytes // authorize email auth := smtp.PlainAuth("", DIVYA_ADD, DIVYA_PWD, EMAIL_SRV) // setup a context for the mail context := &SmtpTemplateData{"Divya", DIVYA_ADD, RCVR_ADD, subject, body} // set up template temp := template.New("Email Template") temp, err = temp.Parse(TEMPLATE) if err != nil { log.Print("error trying to parse mail template") } // write the mail using template and context err = temp.Execute(&doc, context) if err != nil { log.Print("error trying to execute mail template") } // send mail err = smtp.SendMail(EMAIL_SRV+":"+strconv.Itoa(PORT), auth, DIVYA_ADD, []string{RCVR_ADD}, doc.Bytes()) if err != nil { log.Print("ERROR: attempting to send a mail ", err) } else { fmt.Println("Mail sent successfully!") } }
// NewMailer returns a mailer. The given parameters are used to connect to the // SMTP server via a PLAIN authentication mechanism. func NewMailer(host string, username string, password string, port int, settings ...MailerSetting) *Mailer { return NewCustomMailer( fmt.Sprintf("%s:%d", host, port), smtp.PlainAuth("", username, password, host), settings..., ) }
func (mod *EmailBee) Action(action bees.Action) []bees.Placeholder { outs := []bees.Placeholder{} switch action.Name { case "send": to := "" text := "" subject := "" for _, opt := range action.Options { if opt.Name == "text" { text = opt.Value.(string) } if opt.Name == "recipient" { to = opt.Value.(string) } if opt.Name == "subject" { subject = opt.Value.(string) } } text = "Subject: " + subject + "\n\n" + text auth := smtp.PlainAuth("", mod.username, mod.password, mod.server[:strings.Index(mod.server, ":")]) err := smtp.SendMail(mod.server, auth, mod.username, []string{to}, []byte(text)) if err != nil { panic(err) } default: panic("Unknown action triggered in " + mod.Name() + ": " + action.Name) } return outs }
// Send will send out the mail func (e *Email) Send() error { if e.Auth == nil { e.Auth = smtp.PlainAuth(e.Identity, e.Username, e.Password, e.Host) } // Merge the To, Cc, and Bcc fields to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc)) to = append(append(append(to, e.To...), e.Cc...), e.Bcc...) // Check to make sure there is at least one recipient and one "From" address if len(to) == 0 { return errors.New("Must specify at least one To address") } from, err := mail.ParseAddress(e.Username) if err != nil { return err } if len(e.From) == 0 { e.From = e.Username } // use mail's RFC 2047 to encode any string e.Subject = qEncode("utf-8", e.Subject) raw, err := e.Bytes() if err != nil { return err } return smtp.SendMail(e.Host+":"+strconv.Itoa(e.Port), e.Auth, from.Address, to, raw) }
// Send sends an email message. func Send(msg *Message) error { // retieve the system settings from the database // so that we can get the SMTP details. s, err := database.GetSettings() if err != nil { log.Print(err) return err } // set the FROM address msg.Sender = s.SmtpAddress // format the raw email message body body := fmt.Sprintf(emailTemplate, msg.Sender, msg.To, msg.Subject, msg.Body) var auth smtp.Auth if len(s.SmtpUsername) > 0 { auth = smtp.PlainAuth("", s.SmtpUsername, s.SmtpPassword, s.SmtpServer) } addr := fmt.Sprintf("%s:%s", s.SmtpServer, s.SmtpPort) err = smtp.SendMail(addr, auth, msg.Sender, []string{msg.To}, []byte(body)) if err != nil { log.Print(err) return err } return nil }
//NewEmailServerFromService - construct email server from vCap Service func NewEmailServerFromService(appEnv *cfenv.App) *EmailServer { serviceName := os.Getenv("SMTP_SERVICE_NAME") hostName := os.Getenv("SMTP_HOST") portName := os.Getenv("SMTP_PORT") userName := "" passName := "" supportEmail := os.Getenv("SUPPORT_EMAIL") service, err := appEnv.Services.WithName(serviceName) if err != nil { panic(fmt.Sprintf("email service name error: %s", err.Error())) } if service.Credentials[hostName] == nil { panic(fmt.Sprintf("credentials contains a nil value for (%s, %s or %s): %v", userName, passName, hostName, service.Credentials)) } auth := smtp.PlainAuth("", userName, passName, service.Credentials[hostName].(string)) port, err := strconv.Atoi(service.Credentials[portName].(string)) if err != nil { panic(fmt.Sprintf("The port for email server is not a valid integer %s", err.Error())) } return &EmailServer{ host: service.Credentials[hostName].(string), port: port, auth: auth, sendMailFunc: DefaultSMTPSendEmail, supportEmail: service.Credentials[supportEmail].(string), } }
func readInEmailer(in *Input) (*Emailer, error) { auths, err := readLine(in, 4, "Need four fields in the first line of the input file: identity,username,password,host") if err != nil { return nil, err } sp, err := readLine(in, 2, "Need two fields in the second line of the input file: server,from") if err != nil { return nil, err } subject, err := readLine(in, -1, "Need a line designating the subject in the third line of the file") if err != nil { return nil, err } msg, err := readLine(in, -1, "Need a line designating the generic message in the fourth line of the file") if err != nil { return nil, err } raw := "Subject: " + subject[0] + "\r\nContent-Type: text/html\r\n\r\n" + msg[0] if line, b := in.Next(); b { return nil, errors.New("Extra line at the end of the first section: " + line) } return &Emailer{ auth: smtp.PlainAuth(auths[0], auths[1], auths[2], auths[3]), server: sp[0], from: sp[1], rawMsg: raw, }, nil }
// newSMTPClient will connect, auth, say helo to the SMTP server and return the client. func newSMTPClient(username, password, host string, port int) (*smtp.Client, error) { addr := fmt.Sprintf("%s:%d", host, port) client, err := smtp.Dial(addr) if err != nil { return client, err } // just saying HELO! if err = client.Hello("localhost"); err != nil { return client, err } // if the server can handle TLS, use it if ok, _ := client.Extension("STARTTLS"); ok { if err = client.StartTLS(nil); err != nil { return client, err } } // if the server can handle auth, use it if ok, _ := client.Extension("AUTH"); ok { auth := smtp.PlainAuth("", username, password, host) if err = client.Auth(auth); err != nil { return client, err } } return client, nil }
func main() { var smtp_server = flag.String("server", "", "the server to use smtp (example smtp.gmail.com)") var smtp_port = flag.String("port", "", "the server port to use smtp (example 587)") var user = flag.String("u", "", "the user for the server") var pass = flag.String("p", "", "the password for the user") var tos = flag.String("t", "", "comma seperated list of to emails (example: [email protected],[email protected]") var subject = flag.String("s", "", "the subject for the email") var body = flag.String("b", "", "the body for the email") flag.Parse() if *smtp_server == "" { fmt.Println("you didn't specify a server. do so with -server") os.Exit(1) } if *smtp_port == "" { fmt.Println("you didn't specify a server port. do so with -port") os.Exit(1) } if *user == "" { fmt.Println("you didn't specify a user. do so with -u") os.Exit(1) } if *pass == "" { fmt.Println("you didn't specify a password for the user. do so with -p") os.Exit(1) } if *tos == "" { fmt.Println("you didn't specify at least one user. do so with -t") os.Exit(1) } toArr := strings.Split(*tos, ",") auth := smtp.PlainAuth("", *user, *pass, *smtp_server) err := smtp.SendMail(*smtp_server+":"+*smtp_port, auth, *user, toArr, []byte("subject:"+*subject+"\n"+*body), ) if err != nil { fmt.Println(err) } fmt.Println("email sent sucessfully") }
func newSMTPClient(conn net.Conn, config *model.Config) (*smtp.Client, *model.AppError) { c, err := smtp.NewClient(conn, config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort) if err != nil { l4g.Error("Failed to open a connection to SMTP server %v", err) return nil, model.NewAppError("SendMail", "Failed to open TLS connection", err.Error()) } // GO does not support plain auth over a non encrypted connection. // so if not tls then no auth auth := smtp.PlainAuth("", config.EmailSettings.SMTPUsername, config.EmailSettings.SMTPPassword, config.EmailSettings.SMTPServer+":"+config.EmailSettings.SMTPPort) if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_TLS { if err = c.Auth(auth); err != nil { return nil, model.NewAppError("SendMail", "Failed to authenticate on SMTP server", err.Error()) } } else if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_STARTTLS { tlsconfig := &tls.Config{ InsecureSkipVerify: true, ServerName: config.EmailSettings.SMTPServer, } c.StartTLS(tlsconfig) if err = c.Auth(auth); err != nil { return nil, model.NewAppError("SendMail", "Failed to authenticate on SMTP server", err.Error()) } } return c, nil }
// Send sends the email, returning any error encountered. func (e *Email) Send() error { if e.From == "" { return errors.New("Error: No sender specified. Please set the Email.From field.") } if e.To == nil || len(e.To) == 0 { return errors.New("Error: No recipient specified. Please set the Email.To field.") } if e.Password == "" { return errors.New("Error: No password specified. Please set the Email.Password field.") } auth := smtp.PlainAuth( "", e.From, e.Password, "smtp.gmail.com", ) conn, err := smtp.Dial("smtp.gmail.com:587") if err != nil { return err } err = conn.StartTLS(&tls.Config{}) if err != nil { return err } err = conn.Auth(auth) if err != nil { return err } err = conn.Mail(e.From) if err != nil { if strings.Contains(err.Error(), "530 5.5.1") { return errors.New("Error: Authentication failure. Your username or password is incorrect.") } return err } for _, recipient := range e.To { err = conn.Rcpt(recipient) if err != nil { return err } } wc, err := conn.Data() if err != nil { return err } defer wc.Close() _, err = wc.Write(e.Bytes()) if err != nil { return err } return nil }
func TestAuthRejection(t *testing.T) { addr, closer := runsslserver(t, &smtpd.Server{ Authenticator: func(peer smtpd.Peer, username, password string) error { return smtpd.Error{Code: 550, Message: "Denied"} }, ForceTLS: true, }) defer closer() c, err := smtp.Dial(addr) if err != nil { t.Fatalf("Dial failed: %v", err) } if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil { t.Fatalf("STARTTLS failed: %v", err) } if err := c.Auth(smtp.PlainAuth("foo", "foo", "bar", "127.0.0.1")); err == nil { t.Fatal("Auth worked despite rejection") } }
func getAuth() smtp.Auth { return smtp.PlainAuth("", g_servinfo.username, g_servinfo.password, g_servinfo.server, ) }
func SendEmail(email *Email) error { auth := smtp.PlainAuth("", USER, PASSWORD, HOST) sendTo := strings.Split(email.to, ";") done := make(chan error, 1024) go func() { defer close(done) for _, v := range sendTo { str := strings.Replace("From: "+USER+"~To: "+v+"~Subject: "+email.subject+"~~", "~", "\r\n", -1) + email.msg err := smtp.SendMail( SERVER_ADDR, auth, USER, []string{v}, []byte(str), ) done <- err } }() for i := 0; i < len(sendTo); i++ { <-done } return nil }
// auth resolves a string of authentication mechanisms. func (n *Email) auth(mechs string) (smtp.Auth, error) { username := n.conf.AuthUsername for _, mech := range strings.Split(mechs, " ") { switch mech { case "CRAM-MD5": secret := string(n.conf.AuthSecret) if secret == "" { continue } return smtp.CRAMMD5Auth(username, secret), nil case "PLAIN": password := string(n.conf.AuthPassword) if password == "" { continue } identity := n.conf.AuthIdentity // We need to know the hostname for both auth and TLS. host, _, err := net.SplitHostPort(n.conf.Smarthost) if err != nil { return nil, fmt.Errorf("invalid address: %s", err) } return smtp.PlainAuth(identity, username, password, host), nil } } return nil, nil }
func SendEmail(to, subject, title, body string) bool { hp := strings.Split(host, ":") auth := smtp.PlainAuth("", username, password, hp[0]) var content_type string mailtype := "html" if mailtype == "html" { content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8" } else { content_type = "Content-Type: text/plain" + "; charset=UTF-8" } // 登录之 body = strings.Replace(bodyTpl, "$body", body, 1) body = strings.Replace(body, "$title", title, 1) msg := []byte("To: " + to + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body) send_to := strings.Split(to, ";") err := smtp.SendMail(host+":"+port, auth, username, send_to, msg) if err != nil { return false } return true }
func sendMail(subject, content string, tos []string) error { message := `From: Revel社区 To: ` + strings.Join(tos, ",") + ` Subject: ` + subject + ` Content-Type: text/html;charset=UTF-8 ` + content if Smtp.username == "" { path, _ := filepath.Abs("") c, _ := config.ReadDefault(fmt.Sprintf("%s/src/revelapp/conf/my.conf", path)) Smtp.username, _ = c.String("smtp", "smtp.username") Smtp.password, _ = c.String("smtp", "smtp.password") Smtp.address, _ = c.String("smtp", "smtp.address") Smtp.from, _ = c.String("smtp", "smtp.from") Smtp.host, _ = c.String("smtp", "smtp.host") } auth := smtp.PlainAuth("", Smtp.username, Smtp.password, Smtp.host) err := smtp.SendMail(Smtp.address, auth, Smtp.from, tos, []byte(message)) if err != nil { fmt.Println(err) return err } return nil }