Golang SendMail示例

说明

golang sendmail示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/smtp

示例#1
文件: esmail.go 项目: amundi/eschecker.v2

func (m Mail) DoRequest() {
	var err error

	if isAuth() {
		err = smtp.SendMail(
			g_servinfo.server+":"+strconv.Itoa(g_servinfo.port),
			getAuth(),
			g_servinfo.username,
			m.to,
			[]byte(m.Header.getFullHeader()+fmt.Sprintf(EMAIL_TEMPLATE, m.subject, m.subject, m.body)+RN),
		)
	} else {
		err = smtp.SendMail(
			g_servinfo.server+":"+strconv.Itoa(g_servinfo.port),
			nil,
			g_servinfo.username,
			m.to,
			[]byte(m.Header.getFullHeader()+fmt.Sprintf(EMAIL_TEMPLATE, m.subject, m.subject, m.body)+RN),
		)
	}

	if err != nil {
		eslog.Error("%s : error sending mail : "+err.Error(), os.Args[0])
	}
}

示例#2
文件: server.go 项目: andrewstucki/mailer

func (e *Email) Send() error {
	var err error
	var servers = make([]string, 0)

	mailTokens := strings.Split(inboxAddress, "@")
	domain := mailTokens[len(mailTokens)-1]

	mxServers, err := net.LookupMX(domain)
	if err != nil {
		return err
	}
	for _, server := range mxServers {
		servers = append(servers, fmt.Sprintf("%s:25", strings.TrimRight(server.Host, ".")))
	}

	for _, server := range servers {
		msg, err := e.ConstructMessage()
		if err == nil {
			log.Printf("Attempting send to: %s, smtp_from: %s, rcpt_to: %s, message: %s\n", server, outboundSender, inboxAddress, string(msg))
			err = smtp.SendMail(
				server,
				nil,
				outboundSender,
				[]string{inboxAddress},
				msg,
			)
			if err == nil {
				break
			} else {
				log.Printf("Received error from mx server: %s\n", err.Error())
			}
		}
	}
	return err
}

示例#3
文件: email.go 项目: flyeven/email

// Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
// This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
func (e *Email) Send(addr string, a smtp.Auth) error {
	// 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...)
	for i := 0; i < len(to); i++ {
		addr, err := mail.ParseAddress(to[i])
		if err != nil {
			return err
		}
		to[i] = addr.Address
	}
	// Check to make sure there is at least one recipient and one "From" address
	if e.From == "" || len(to) == 0 {
		return errors.New("Must specify at least one From address and one To address")
	}
	from, err := mail.ParseAddress(e.From)
	if err != nil {
		return err
	}
	raw, err := e.Bytes()
	if err != nil {
		return err
	}
	return smtp.SendMail(addr, a, from.Address, to, raw)
}

示例#4
文件: uptime.go 项目: jrsmith/uptime.go

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")
	}

}

示例#5
文件: mail.go 项目: cokeboL/beego

// 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)
}

示例#6
文件: emailbee.go 项目: Horrendus/beehive

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
}

示例#7
文件: mail.go 项目: vito/drone

// 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
}

示例#8
文件: mail.go 项目: gotstago/go-tarabish

func SendMail(to []string, subject, message string) error {
	var doc bytes.Buffer

	ctx := struct {
		From    string
		To      string
		Subject string
		Body    string
	}{
		fromEmail,
		strings.Join(to, ", "),
		subject,
		message,
	}

	if err := emailTemplate.Execute(&doc, ctx); err != nil {
		return err
	}

	return smtp.SendMail(
		fmt.Sprintf("%v:%v", authParts["EMAIL_HOST"], authParts["EMAIL_PORT"]),
		auth,
		fromEmail,
		to,
		doc.Bytes())
}

示例#9
文件: smtp.go 项目: nirekin/mysqlbatch

// 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)
	}
}

示例#10
文件: gletter.go 项目: gustavokuklinski/gletter

// SetMail use the parameters on the Struct to send e-mails
func SetMail(Config MailConfig) {

	// Get the Auth
	mauth := smtp.PlainAuth(
		"",
		Config.MailSender,   // Sender e-mail
		Config.MailPassword, // Sender password
		Config.Server,       // Server. Eg: smtp.google.com
	)

	emailFrom := []string{Config.MailReceiver}
	emailHeader := "To:" + Config.MailReceiver + "\r\nSubject:" + Config.Subject + "\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=ISO-8891-1\r\n\r\n"

	emailBody := []byte(emailHeader + Config.Message)
	// Send the e-mail
	err := smtp.SendMail(
		Config.Server+":"+strconv.Itoa(Config.Port), // Server + Port
		mauth,             // Get the Auth setup
		Config.MailSender, // Get who is sending the e-mail
		emailFrom,         // Get who will receive the e-mail
		emailBody,         // Get the message
	)

	if err != nil {
		log.Fatal(err) // Log if error
	} else {
		log.Println("E-Mail send to: " + Config.MailReceiver) // Log if succeful and display who receive the e-mail
	}

}

示例#11
文件: smtp.go 项目: hellboysdnu/beego

func (s *SmtpWriter) WriteMsg(msg string, level int) error {
	if level < s.level {
		return nil
	}

	hp := strings.Split(s.host, ":")

	// Set up authentication information.
	auth := smtp.PlainAuth(
		"",
		s.username,
		s.password,
		hp[0],
	)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	content_type := "Content-Type: text/plain" + "; charset=UTF-8"
	mailmsg := []byte("To: " + strings.Join(s.recipientAddresses, ";") + "\r\nFrom: " + s.username + "<" + s.username +
		">\r\nSubject: " + s.subject + "\r\n" + content_type + "\r\n\r\n" + msg)
	err := smtp.SendMail(
		s.host,
		auth,
		s.username,
		s.recipientAddresses,
		mailmsg,
	)
	return err
}

示例#12
文件: thankyou.go 项目: klec/thankyou

func (a *Application) sendEmail(address string, action string) {
	auth := smtp.PlainAuth(
		"",
		"[email protected]",
		"Ryurik13",
		"smtp.gmail.com",
	)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	fmt.Println("sending email")
	mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
	subject := "Subject: О тебе кто то отзыв оставил\n"
	message := "<html><body>Кто то накапал что ты " + action + ". <br>\nМожешь не обращать внимание," +
		"а можешь оставить <a href=\"http://klec.od:8080/index.html\">здесь</a> ответный отзыв или просто упомянуть кого то, кто тебе помогал на днях.<br>\n" +
		"Глядишь ему на том свете зачтется... Ну или при выдаче ЗП.</body></html>"
	err := smtp.SendMail(
		"smtp.gmail.com:25",
		auth,
		"[email protected]",
		[]string{address},
		[]byte(subject+mime+message),
	)
	if err != nil {
		fmt.Println(err)
	}
}

示例#13
文件: email_server.go 项目: rightjoin/mailman

func (s *EmailServer) dispatchMessage(m *Message) error {
	var e email.Email
	//err := ds.LoadStruct(&e, []byte(m.Data))
	err := ds.Load(&e, []byte(m.Data))
	if err != nil {
		return err
	}

	// 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...)
	for i := 0; i < len(to); i++ {
		addr, err := mail.ParseAddress(to[i])
		if err != nil {
			return err
		}
		to[i] = addr.Address
	}

	// Check to make sure there is at least one recipient and one "From" address
	if e.From == "" || len(to) == 0 {
		return errors.New("Must specify at least one From address and one To address")
	}
	from, err := mail.ParseAddress(e.From)
	if err != nil {
		return err
	}
	raw, err := e.Bytes()
	if err != nil {
		return err
	}

	return smtp.SendMail(s.address, s.auth, from.Address, to, raw)
}

示例#14
文件: mailer.go 项目: duanqy/retask

func (m *Mailer) SendMail(to, subject, body, contentType string) error {
	auth := smtp.PlainAuth("", m.User, m.Password, m.Host)
	msg := []byte("To: " + to + "\r\nFrom: " + m.User + ">\r\nSubject: " + "\r\n" + contentType + "\r\n\r\n" + body)
	sendTo := strings.Split(to, ";")
	err := smtp.SendMail(fmt.Sprintf("%s:%d", m.Host, m.Port), auth, m.User, sendTo, msg)
	return err
}

示例#15
文件: email.go 项目: pubnative/statusboard

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))
}

示例#16
文件: divya_ga.go 项目: jinseokYeom/HackTX2015

// 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!")
	}
}

示例#17
文件: EmailService.go 项目: nosqldb/zhujian

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
}

示例#18
文件: mail.go 项目: tzm529/studygo

func sendMail() {
	for {
		msg := <-msgChan
		fmt.Printf("to=%s,subject=%s\n", msg.To, msg.Subject)
		header := make(map[string]string)
		header["From"] = defaultFrom.String()
		header["To"] = msg.To
		header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(msg.Subject)))
		header["MIME-Version"] = "1.0"
		header["Content-Type"] = "text/html; charset=UTF-8"
		header["Content-Transfer-Encoding"] = "base64"

		message := ""

		for k, v := range header {
			message += fmt.Sprintf("%s: %s\r\n", k, v)
		}
		message += "\r\n" + b64.EncodeToString([]byte(msg.Body))
		//auth := smtp.PlainAuth("", "", "", host)
		//err := smtp.SendMail(host, auth, "[email protected]", []string{to.Address}, []byte(message))
		err := smtp.SendMail(*paramHost+":"+*paramPort, nil, *paramFromEmail, []string{msg.To}, []byte(message))
		if err == nil {
			fmt.Println("send success")
		} else {
			fmt.Println(err)
		}
	}
}

示例#19
文件: gomail.go 项目: asharif/gomail

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")
}

示例#20
文件: mail.go 项目: AlexanderGrom/componenta

//
// Отправка
//
func (self *Mail) Send() error {
	headers := self.headers.Headers()

	for _, v := range []string{"From", "To", "Subject"} {
		if _, ok := headers[v]; !ok {
			return errors.New("Mail: not \"" + v + "\" header")
		}
	}

	buf := &bytes.Buffer{}
	for k, v := range headers {
		buf.WriteString(k)
		buf.WriteString(": ")
		buf.WriteString(v)
		buf.WriteString("\r\n")
	}
	buf.WriteString("\r\n")
	buf.WriteString(self.body.Body())

	msg := buf.Bytes()

	err = smtp.SendMail("localhost:25", nil, self.from, []string{self.to}, msg)

	if err != nil {
		return err
	}
}

示例#21
文件: comm.go 项目: jsli/gorevel

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
}

示例#22
文件: gmail.go 项目: jmptrader/down-low

// 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{"[email protected]"},
		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)
	}
}

示例#23
文件: web.go 项目: arlm/diplicity

func (self *Web) SendMail(fromName, replyTo, subject, message string, recips []string) (err error) {
	body := strings.Join([]string{
		"Content-Type: text/plain; charset=\"utf-8\"",
		fmt.Sprintf("Reply-To: %v", replyTo),
		fmt.Sprintf("From: %v <%v>", fromName, self.smtpAccount),
		fmt.Sprintf("To: %v", strings.Join(recips, ", ")),
		fmt.Sprintf("Subject: %v", subject),
		"",
		message,
	}, "\r\n")
	actualRecips := []string{}
	for _, recip := range recips {
		if match := gmail.AddrReg.FindString(recip); match != "" {
			actualRecips = append(actualRecips, match)
		}
	}
	if self.Env() == Development {
		self.Infof("Would have sent\n%v", body)
	} else {
		key := uint64(time.Now().UnixNano()<<32) + uint64(rand.Uint32())
		self.Infof("%v: Will try to send\n%v", key, body)
		if err = smtp.SendMail(self.smtpHost, nil, self.smtpAccount, actualRecips, []byte(body)); err != nil {
			self.Errorf("%v: Unable to send: %v", key, err)
			return
		}
		self.Infof("%v: Successfully sent", key)
	}
	return
}

示例#24
文件: writers_smtpwriter.go 项目: haowang1013/seelog

// Write pushes a text message properly composed according to RFC 5321
// to a post server, which sends it to the recipients.
func (smtpw *smtpWriter) Write(data []byte) (int, error) {
	var err error
	if smtpw.caCertDirPaths == nil {
		err = smtp.SendMail(
			smtpw.hostNameWithPort,
			smtpw.auth,
			smtpw.senderAddress,
			smtpw.recipientAddresses,
			prepareMessage(smtpw.senderAddress, smtpw.senderName, subjectPhrase, data),
		)
	} else {
		config, e := getTLSConfig(smtpw.caCertDirPaths, smtpw.hostName)
		if e != nil {
			return 0, e
		}
		err = sendMailWithTLSConfig(
			config,
			smtpw.hostNameWithPort,
			smtpw.auth,
			smtpw.senderAddress,
			smtpw.recipientAddresses,
			prepareMessage(smtpw.senderAddress, smtpw.senderName, subjectPhrase, data),
		)
	}
	if err != nil {
		return 0, err
	}
	return len(data), nil
}

示例#25
文件: mail.go 项目: tulir293/mauirc-server

// 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))
	}
}

示例#26
文件: feedmailer.go 项目: jroimartin/gfm

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
}

示例#27
文件: sendMail.go 项目: sshitaime/go-study

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
}

示例#28
文件: main.go 项目: amruthv/Dionysus

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)
	}
}

示例#29
文件: Email.go 项目: jianping11/leanote

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
}

示例#30
文件: email.go 项目: cention-mujibur-rahman/go-in-practice

func main() {
	message := &EmailMessage{
		From:    "[email protected]",
		To:      "[email protected]",
		Subject: "A test",
		Body:    "Just saying hi",
	}

	var body bytes.Buffer
	t.Execute(&body, message)

	fmt.Printf("%s", body.Bytes())

	authCreds := &EmailCredentials{
		Username: "myUsername",
		Password: "myPass",
		Server:   "smtp.example.com",
		Port:     25,
	}

	auth := smtp.PlainAuth("",
		authCreds.Username,
		authCreds.Password,
		authCreds.Server,
	)

	smtp.SendMail(authCreds.Server+":"+strconv.Itoa(authCreds.Port),
		auth,
		message.From,
		message.To,
		body.Bytes())
}

展开阅读全文