Ejemplo n.º 1
0
func sendResetPasswordEmail(member Member) {
	templateFile := "./templates/resetpasswordemail.html"
	templateData, err := ioutil.ReadFile(templateFile)

	resetPasswordUri := fmt.Sprintf("%s?t=%s", getResetPasswordUri(), member.Password_reset_token)
	body := strings.Replace(string(templateData), "<<memberEmail>>", member.Email, -1)
	body = strings.Replace(body, "<<resetPasswordUri>>", resetPasswordUri, -1)

	// Set up authentication information.
	// https://gist.github.com/andelf/5004821
	auth := smtp.PlainAuth("", getSmtpUser(), getSmtpPass(), getSmtpHost())

	from := mail.Address{"Support", getSmtpUser()}
	to := mail.Address{member.Email, member.Email}
	title := "Reset password"
	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = title
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString([]byte(body))

	err = smtp.SendMail(getSmtpHost()+getSmtpPort(), auth, from.Address, []string{to.Address}, []byte(message))
	if err != nil {
		fmt.Println(err)
	}
}
Ejemplo n.º 2
0
func main() {
	host := "192.168.0.243:25"

	from := mail.Address{"发件人", "*****@*****.**"}
	to := mail.Address{"收件人", "*****@*****.**"}
	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte("标题测试")))
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/html; charset=UTF-8"
	header["Content-Transfer-Encoding"] = "base64"

	body := "邮件正文"

	message := ""

	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + b64.EncodeToString([]byte(body))
	//auth := smtp.PlainAuth("", "", "", host)
	err := smtp.SendMail(host, nil, "*****@*****.**", []string{to.Address}, []byte(message))
	fmt.Println(err)
}
Ejemplo n.º 3
0
// FundraisingPagesForCharityAndUser returns the charity's fundraising pages registered with the specified JustGiving user account
func (svc *Service) FundraisingPagesForCharityAndUser(charityID uint, account mail.Address) ([]*FundraisingPageRef, error) {

	var results []*FundraisingPageRef

	// mail.Address stores email in the format <*****@*****.**>, this simply removes the `<` `>`
	em := account.String()
	if em != "" {
		em = em[1 : len(em)-1]
	}

	method := "GET"
	path := bytes.NewBuffer([]byte(svc.BasePath))
	path.WriteString("/")
	path.WriteString(svc.APIKey)
	path.WriteString("/v1/account/")
	path.WriteString(em)
	path.WriteString("/pages/?charityId=")
	path.WriteString(strconv.FormatUint(uint64(charityID), 10))

	req, err := api.BuildRequest(UserAgent, ContentType, method, path.String(), nil)
	if err != nil {
		return nil, err
	}
	res, resBody, err := api.Do(svc.client, svc.origin, "FundraisingPagesForCharityAndUser", req, "", svc.HTTPLogger)
	if err != nil {
		return nil, err
	}

	if res.StatusCode == 404 {
		return results, nil
	}

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("invalid response %s", res.Status)
	}

	var result = []struct {
		EventID       uint   `json:"eventId"`
		PageID        uint   `json:"pageId"`
		PageShortName string `json:"pageShortName"`
	}{}

	if err := json.Unmarshal([]byte(resBody), &result); err != nil {
		return nil, fmt.Errorf("invalid response %v", err)
	}

	for _, p := range result {
		if p.PageID > 0 {
			results = append(results, &FundraisingPageRef{
				charityID: charityID,
				eventID:   p.EventID,
				id:        p.PageID,
				shortName: p.PageShortName,
			})

		}
	}

	return results, nil
}
Ejemplo n.º 4
0
// RequestPasswordReminder requests JustGiving to send a password reset email
func (svc *Service) RequestPasswordReminder(account mail.Address) error {

	method := "GET"

	// mail.Address stores email in the format <*****@*****.**>, we don't want the `<` `>`
	em := account.String()
	em = em[1 : len(em)-1]

	path := bytes.NewBuffer([]byte(svc.BasePath))
	path.WriteString("/")
	path.WriteString(svc.APIKey)
	path.WriteString("/v1/account/")
	path.WriteString(em)
	path.WriteString("/requestpasswordreminder")

	req, err := api.BuildRequest(UserAgent, ContentType, method, path.String(), nil)
	if err != nil {
		return err
	}

	res, _, err := api.Do(svc.client, svc.origin, "RequestPasswordReminder", req, "", svc.HTTPLogger)
	if err != nil {
		return err
	}

	if res.StatusCode != 200 {
		return fmt.Errorf("invalid response %s", res.Status)
	}
	return nil

}
Ejemplo n.º 5
0
// Message to render a ses.SendEmailInput
func Message(Sender *mail.Address, ToUsers []*mail.Address, Subject,
	Content string) *ses.SendEmailInput {

	var mailCharset = aws.String("UTF-8")
	var toUsers []*string

	toUsers = make([]*string, len(ToUsers))
	for i, v := range ToUsers {
		toUsers[i] = aws.String(v.String())
	}

	return &ses.SendEmailInput{
		Destination: &ses.Destination{
			ToAddresses: toUsers,
		},
		Message: &ses.Message{
			Body: &ses.Body{
				HTML: &ses.Content{
					Charset: mailCharset,
					Data:    aws.String(Content),
				},
			},
			Subject: &ses.Content{
				Charset: mailCharset,
				Data:    aws.String(Subject),
			},
		},
		Source: aws.String(Sender.String()),
	}
}
Ejemplo n.º 6
0
func sendEmail(senderFunc mailSender, smtpConfig smtpConfiguration, ts time.Time, errors []verificationError) error {
	// set up possible authentication
	var auth smtp.Auth
	if smtpConfig.Auth != nil {
		a := *smtpConfig.Auth
		auth = smtp.PlainAuth(
			"",
			a.Username,
			a.Password,
			smtpConfig.Host,
		)
	} else {
		auth = nil
	}

	from := mail.Address{Address: smtpConfig.From}
	toString := makeToAddresses(smtpConfig.To)

	title := "Ismonitor alert"

	body := makeMessage(errors)

	message := makeHeaders(from.String(), toString, title, ts) // headers
	message += "\r\n"
	message += base64.StdEncoding.EncodeToString([]byte(body)) // body

	return senderFunc(
		smtpConfig.Host+":"+fmt.Sprintf("%d", smtpConfig.Port),
		auth,
		from.Address,
		smtpConfig.To,
		[]byte(message))
}
Ejemplo n.º 7
0
func NewMessage(from, to *mail.Address, subject string, files []string, templatePath,
	htmlTemplatePath string, context interface{}) (*email.Email, error) {
	msg := &email.Email{
		From:    from.String(),
		To:      []string{to.String()},
		Subject: subject,
	}

	for _, file := range files {
		_, err := msg.AttachFile(file)
		if err != nil {
			return nil, err
		}
	}

	if templatePath != "" {
		parsed, err := parseTemplate(templatePath, context)
		if err != nil {
			return nil, err
		}

		msg.Text = parsed
	}

	if htmlTemplatePath != "" {
		parsed, err := parseTemplate(htmlTemplatePath, context)
		if err != nil {
			return nil, err
		}

		msg.HTML = parsed
	}

	return msg, nil
}
Ejemplo n.º 8
0
func sendMail(output []byte, subject string, fromAddress string, toAddresses []string) {
	smtpServer := "smtp.blah.org"
	from := mail.Address{"Code Review Request", "*****@*****.**"}
	auth := smtp.PlainAuth(
		"",
		"*****@*****.**",
		"password",
		smtpServer,
	)
	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = toAddresses[0]
	header["Subject"] = subject
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString(output)

	err := smtp.SendMail(smtpServer+":587", auth, from.Address, toAddresses, []byte(message))
	LogError(err)

	log.Printf("Email sent. %s", strings.Join(toAddresses, ","))
}
Ejemplo n.º 9
0
func SendMail(to, subject, body string) *model.AppError {

	if len(Cfg.EmailSettings.SMTPServer) == 0 || Cfg.EmailSettings.ByPassEmail {
		return nil
	}

	fromMail := mail.Address{Cfg.EmailSettings.FeedbackName, Cfg.EmailSettings.FeedbackEmail}
	toMail := mail.Address{"", to}

	headers := make(map[string]string)
	headers["From"] = fromMail.String()
	headers["To"] = toMail.String()
	headers["Subject"] = html.UnescapeString(subject)
	headers["MIME-version"] = "1.0"
	headers["Content-Type"] = "text/html"

	message := ""
	for k, v := range headers {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n<html><body>" + body + "</body></html>"

	conn, err1 := connectToSMTPServer()
	if err1 != nil {
		return err1
	}
	defer conn.Close()

	c, err2 := newSMTPClient(conn)
	if err2 != nil {
		return err2
	}
	defer c.Quit()
	defer c.Close()

	if err := c.Mail(fromMail.Address); err != nil {
		return model.NewAppError("SendMail", "Failed to add from email address", err.Error())
	}

	if err := c.Rcpt(toMail.Address); err != nil {
		return model.NewAppError("SendMail", "Failed to add to email address", err.Error())
	}

	w, err := c.Data()
	if err != nil {
		return model.NewAppError("SendMail", "Failed to add email messsage data", err.Error())
	}

	_, err = w.Write([]byte(message))
	if err != nil {
		return model.NewAppError("SendMail", "Failed to write email message", err.Error())
	}

	err = w.Close()
	if err != nil {
		return model.NewAppError("SendMail", "Failed to close connection to SMTP server", err.Error())
	}

	return nil
}
Ejemplo n.º 10
0
// AddRecipient will add mail.Address emails to recipients.
func (m *SGMail) AddRecipient(recipient *mail.Address) {
	m.SMTPAPIHeader.AddTo(recipient.String())
	m.To = append(m.To, recipient.Address)
	if recipient.Name != "" {
		m.ToName = append(m.ToName, recipient.Name)
	}
}
Ejemplo n.º 11
0
Archivo: email.go Proyecto: coddo/gost
// SetRecipient sets the receiver of the email
func (email *Email) SetRecipient(address string) {
	var recipient = mail.Address{
		Address: address,
	}

	email.recipient = []string{recipient.Address}
	email.header["To"] = recipient.String()
}
Ejemplo n.º 12
0
func main() {
	addr := mail.Address{"Jim Green", "*****@*****.**"}
	fmt.Println(addr.String())
	// Output: =?utf-8?q?Jim_Green?= <*****@*****.**>
	addr = mail.Address{"中文", "*****@*****.**"}
	fmt.Println(addr.String())
	// Output: =?utf-8?q?=E4=B8=AD=E6=96=87?= <*****@*****.**>
}
Ejemplo n.º 13
0
// SendRecoveryEmail dispatches predefined recovery email to recipient defined in parameters.
// Makes use of https://gist.github.com/andelf/5004821
func SendRecoveryEmail(id, name, address, recovery string) error {

	var email Email
	email.Sender = Settings.Mailer.Login
	email.Host = Settings.URL.String()
	email.Recipient.ID = id
	email.Recipient.Name = name
	email.Recipient.Address = address
	email.Recipient.RecoveryKey = recovery

	from := mail.Address{Settings.Name, email.Sender}
	to := mail.Address{email.Recipient.Name, email.Recipient.Address}
	title := "Password reset"

	t, err := template.New("mail").Parse(RecoveryTemplate)
	if err != nil {
		return err
	}

	var buf bytes.Buffer
	err = t.Execute(&buf, email)
	if err != nil {
		return err
	}

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = title
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; charset=\"utf-8\""
	header["Content-Transfer-Encoding"] = "base64"

	var message string
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + base64.StdEncoding.EncodeToString(buf.Bytes())

	auth := smtp.PlainAuth(
		"",
		Settings.Mailer.Login,
		Settings.Mailer.Password,
		Settings.Mailer.Hostname,
	)

	err = smtp.SendMail(
		fmt.Sprintf("%s:%d", Settings.Mailer.Hostname, Settings.Mailer.Port),
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
	)
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 14
0
func (m *FeedMailer) MakeHeader(recipient mail.Address) string {
	header = make(map[string]string)
	header["MIME-Version"] = "1.0"
	header["From"] = m.Sender.String()
	header["To"] = recipient.String()
	header["Subject"] = "Go lang updates"
	header["Content-type"] = "text/html"
	return toString(header)
}
Ejemplo n.º 15
0
func sendContactFormEmail(smtpUser string,
	smtpPass string,
	smtpServer string,
	to []*mail.Address,
	from *mail.Address,
	subject string,
	body string) error {

	recipients := ""
	toAddresses := make([]string, 0, 10)
	for _, addr := range to {
		toAddresses = append(toAddresses, addr.Address)
		recipients += fmt.Sprintf("%s, ", addr.String())
	}

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = recipients
	header["Subject"] = subject
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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"
	message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))

	auth := smtp.PlainAuth(
		"",
		smtpUser,
		smtpPass,
		smtpServer,
	)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer+":25",
		auth,
		from.Address,
		toAddresses,
		[]byte(message),
	)
	if err != nil {
		log.Printf("Error sending mail: %v", err)
		return err
	} else {
		log.Printf("Sent mail to %s without error: ", recipients)
	}
	log.Println("Finished trying to send email")
	return nil

}
Ejemplo n.º 16
0
// NewMessage builds a new message instance
func NewMessage(from, to *mail.Address, subject string,
	htmlContent string) (*email.Email, error) {
	msg := &email.Email{
		From:    from.String(),
		To:      []string{to.String()},
		Subject: subject,
		HTML:    []byte(htmlContent),
	}

	return msg, nil
}
Ejemplo n.º 17
0
// should be run in a go routine
func (s *Server) sendRecoveryMail(goldHost string, IP string, to []string, link string) {
	if &s.Config.SMTPConfig == nil {
		s.debug.Println("Missing smtp server configuration")
	}
	subject := "Recovery instructions for your account on " + goldHost
	smtpCfg := &s.Config.SMTPConfig

	auth := smtp.PlainAuth("",
		smtpCfg.User,
		smtpCfg.Pass,
		smtpCfg.Host,
	)

	// Setup headers
	src := mail.Address{Name: "", Address: smtpCfg.Addr}
	dst := mail.Address{Name: "", Address: to[0]}
	headers := make(map[string]string)
	headers["From"] = src.String()
	headers["To"] = dst.String()
	headers["Subject"] = subject
	headers["MIME-Version"] = "1.0"
	headers["Content-Type"] = "text/html; charset=\"utf-8\""
	// Setup message
	vals := make(map[string]string)
	vals["{{.IP}}"] = IP
	vals["{{.From}}"] = smtpCfg.Name
	vals["{{.Link}}"] = link
	body := parseMailTemplate("accountRecovery", vals)

	message := ""
	for k, v := range headers {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + body

	if len(smtpCfg.Host) > 0 && smtpCfg.Port > 0 && auth != nil {
		smtpServer := smtpCfg.Host + ":" + strconv.Itoa(smtpCfg.Port)
		var err error
		// force upgrade to full SSL/TLS connection
		if smtpCfg.ForceSSL {
			err = s.sendSecureRecoveryMail(src, dst, []byte(message), smtpCfg)
		} else {
			err = smtp.SendMail(smtpServer, auth, smtpCfg.Addr, to, []byte(message))
		}
		if err != nil {
			s.debug.Println("Error sending recovery email to " + to[0] + ": " + err.Error())
		} else {
			s.debug.Println("Successfully sent recovery email to " + to[0])
		}
	} else {
		s.debug.Println("Missing smtp server and/or port")
	}
}
Ejemplo n.º 18
0
func makeToAddresses(to []string) string {
	var toString string
	for i, t := range to {
		ma := mail.Address{Address: t}
		toString += ma.String()
		if i != len(to)-1 {
			// add comma between addresses unless it's the last one
			toString += ", "
		}
	}
	return toString
}
Ejemplo n.º 19
0
func SendAlertEmail(receiver, alert string) error {
	// Set up authentication information.

	auth := smtp.PlainAuth("", SecretOption["smtp_username"], SecretOption["smtp_password"], SecretOption["smtp_host"])

	from := mail.Address{"BTCRobot监控中心", SecretOption["smtp_username"]}
	to := mail.Address{"收件人", receiver}
	title := "BTCRobot来电--->" + alert

	body := `
	<html>
	<body>
	<h3>
	%s
	</h3>
	<p>
	捐助BTC,支持开发<span style="font-size: 80%"><a href="bitcoin:1NDnnWCUu926z4wxA3sNBGYWNQD3mKyes8">1NDnnWCUu926z4wxA3sNBGYWNQD3mKyes8</a></span>
	</p>
	</body>
	</html>
	`
	body = fmt.Sprintf(body, alert)

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	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" + base64.StdEncoding.EncodeToString([]byte(body))

	logger.Debugln("Try sending Mail to", to)
	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		SecretOption["smtp_addr"],
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message))
	if err != nil {
		logger.Infoln("Send Mail to", to, "error:", err)
		return err
	}
	logger.Debugln("Send Mail to", to, "Successfully")
	return nil
}
Ejemplo n.º 20
0
// CreateMailFromItem returns a Message containing the given story.
func CreateMailFromItem(from string, to mail.Address, item *feed.Story) *gomail.Message {
	content := FormatMessageBody(item)
	gmsg := gomail.NewMessage()
	gmsg.SetHeader("From", from)
	gmsg.SetHeader("To", to.String())
	gmsg.SetHeader("Subject", item.Title)
	gmsg.SetBody("text/html", content)
	if !item.Published.IsZero() {
		gmsg.SetHeader("Date", item.Published.UTC().Format(time.RFC822))
	}
	return gmsg
}
Ejemplo n.º 21
0
func sendEmail(recipientAddress string, subject string, messageBody string) {
	if !credentialsHaveBeenLoaded {
		log.Panic("Outgoing email credentials have not been set. Cannot send message.")
	}

	from := mail.Address{credentials.NoReplyAddressName, credentials.NoReplyAddress}

	headers := make(map[string]string)
	headers["From"] = from.String()
	headers["To"] = recipientAddress
	headers["Subject"] = subject

	message := ""
	for headerName, headerValue := range headers {
		message += fmt.Sprintf("%s: %s\r\n", headerName, headerValue)
	}
	message += "\r\n" + messageBody

	mailAuth := smtp.PlainAuth("", credentials.NoReplyAddress, credentials.NoReplyPassword, credentials.Host)

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         credentials.Host,
	}

	tcpConnection, error := tls.Dial("tcp", credentials.Host+":"+credentials.Port, tlsConfig)
	panicOnError(error)

	smtpClient, error := smtp.NewClient(tcpConnection, credentials.Host)
	panicOnError(error)

	error = smtpClient.Auth(mailAuth)
	panicOnError(error)

	error = smtpClient.Mail(credentials.NoReplyAddress)
	panicOnError(error)

	error = smtpClient.Rcpt(recipientAddress)
	panicOnError(error)

	emailStream, error := smtpClient.Data()
	panicOnError(error)

	_, error = emailStream.Write([]byte(message))
	panicOnError(error)

	error = emailStream.Close()
	panicOnError(error)

	smtpClient.Quit()
}
Ejemplo n.º 22
0
func TestCmdMAIL_Param_Passing(t *testing.T) {
	client, pipe := getTestClient()
	client.Mode = stateMAIL

	testAddr := mail.Address{"First Last", "*****@*****.**"}

	go cmdMAIL(client, "from:First Last <*****@*****.**>")
	_, _, err := pipe.ReadResponse(250)
	if err != nil || client.Mode != stateRCPT || testAddr.String() != client.Message.From().String() {
		t.Errorf("Expected code 250, address %s got: %#v, %s", testAddr, err, client.Message.From())
	}

	pipe.Close()
}
Ejemplo n.º 23
0
// 发送邮件
func SendMail(conf *MailT) error {
	var (
		contentType string
		vs          string
		message     string
		toaddr      mail.Address
	)
	encode := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
	host := strings.Split(conf.Addr, ":")
	auth := smtp.PlainAuth("", conf.User, conf.Pass, host[0])
	if conf.Type == "html" {
		contentType = "text/html; charset=UTF-8"
	} else {
		contentType = "text/plain; charset=UTF-8"
	}
	from := mail.Address{"CmsTop Monitor", conf.From}
	tolist := strings.Split(conf.To, ",")
	to := make([]string, 0)
	for i, addr := range tolist {
		addr = strings.TrimSpace(addr)
		tolist[i] = addr
		toaddr = mail.Address{"", tolist[i]}
		to = append(to, toaddr.String())
	}

	header := make(mail.Header)
	header["From"] = []string{from.String()}
	header["To"] = to
	header["Subject"] = []string{conf.Title}
	header["MIME-Version"] = []string{"1.0"}
	header["Content-Type"] = []string{contentType}
	header["Content-Transfer-Encoding"] = []string{"base64"}

	for k, v := range header {
		vs = strings.Join(v, ", ")
		message += fmt.Sprintf("%s: %s\r\n", k, vs)
	}
	message += "\r\n" + encode.EncodeToString([]byte(conf.Body))

	err := smtp.SendMail(
		conf.Addr,
		auth,
		from.Address,
		tolist,
		[]byte(message),
	)
	return err
}
Ejemplo n.º 24
0
func SendEmail(wrapper *MailerStruct) {

	defer wrapper.wait_group.Done()

	fmt.Println("Sending notifications to ", wrapper.send_mail_to, "...")

	smtpServer := "smtp.postmarkapp.com"
	auth := smtp.PlainAuth(
		"",
		wrapper.smtp_credentials,
		wrapper.smtp_credentials,
		smtpServer,
	)

	from := mail.Address{"FROM_NAME", "*****@*****.**"}
	to := mail.Address{"SystemUser", wrapper.send_mail_to}
	title := "Alert: System Status Check."

	body := fmt.Sprintf("<h3>Hi there,</h3> <p> The server <b>hard drive is almost full.</b> Only <b>%d MBytes</b> left on device. (We should have at least %d Mb) </p> <p>Please contact system administrator to fix this issue.</p> <br/> <hr /> system Monitor", wrapper.mb_available, wrapper.mb_at_least)

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = title
	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" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer+":2525",
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
	)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 25
0
//发送邮件
func SendToMail(toEmail, name string) error {
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	email, _ := conf.Cfg.GetValue("email", "email")
	password, _ := conf.Cfg.GetValue("email", "passwd")
	host, _ := conf.Cfg.GetValue("email", "host")
	subject, _ := conf.Cfg.GetValue("email", "subject")
	sendName, _ := conf.Cfg.GetValue("email", "sendName")

	from := mail.Address{sendName, email}
	to := mail.Address{name, toEmail}

	hp := strings.Split(host, ":")
	auth := smtp.PlainAuth("", email, password, hp[0])

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/html; charset=UTF-8"
	header["Content-Transfer-Encoding"] = "base64"

	//获取用户信息
	userInfo, _, _ := models.GetUserInfo(name)
	EmailMd5 := GetMd5String(toEmail + name + userInfo.Passwd)
	newUser := new(models.User)
	newUser.Email_change = EmailMd5
	err := models.UpdateUser(userInfo.Id, newUser)
	if CheckError("数据库读取失败", err) {
		return err
	}
	body := `<strong>修改密码</strong>
	<p>访问以下网址:<a href="http://` + conf.HttpWeb + `/login/changePasswd?emailCode=` + EmailMd5 + `">http://` + conf.HttpWeb + `/login/changePasswd?emailCode=` + EmailMd5 + `<a><p>
	<p>如果以上链接无法访问,请将该网址复制并粘贴至新的浏览器窗口中。</p>`

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	message += "\r\n" + b64.EncodeToString([]byte(body))

	send_to := strings.Split(toEmail, ";")
	err = smtp.SendMail(host, auth, email, send_to, []byte(message))
	return err
}
Ejemplo n.º 26
0
func SendWithAuthentication() {

	// Set up authentication information.

	smtpServer := "127.0.0.1:2525"
	auth := smtp.PlainAuth(
		"",
		"admin",
		"admin",
		smtpServer,
	)

	from := mail.Address{"example", "*****@*****.**"}
	to := mail.Address{"customer", "*****@*****.**"}
	title := "Mail"

	body := "This is an email confirmation."

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer,
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
		//[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 27
0
func SendCustomMail(emailBody, fromUser, toUser, emailTitle string) {
	// Set up authentication information.

	smtpServer := "smtp.mailgun.org"
	auth := smtp.PlainAuth(
		"",
		"*****@*****.**",
		"44xf4meg4du1",
		smtpServer,
	)

	from := mail.Address{"", fromUser}
	to := mail.Address{"", toUser}
	title := emailTitle

	body := emailBody

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer+":25",
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
	//[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 28
0
func SendEmail(emailto, title, bodyword, authen string) bool {
	// Set up authentication information.
	smtpServer := "smtp.gmail.com"
	auth := smtp.PlainAuth(
		"",
		email,
		emailpass,
		smtpServer,
	)

	from := mail.Address{appname, email}
	to := mail.Address{"收件人", emailto}

	body := bodyword + authen

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer+":25",
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
	)
	if err != nil {
		Log(Log_Struct{"warn", "Email:", err})
		return false
	}

	return true
}
Ejemplo n.º 29
0
func main() {
	//log.Fatal(smtpUser, smtpPass, smtpServer, mesgTo)

	// Set up authentication information.
	auth := smtp.PlainAuth(
		"",
		smtpUser,
		smtpPass,
		smtpServer,
	)

	from := mail.Address{"监控中心", smtpUser}
	to := mail.Address{"收件人", mesgTo}
	title := "当前时段统计报表"

	body := "报表内容一切正常"

	header := make(map[string]string)
	header["From"] = from.String()
	header["To"] = to.String()
	header["Subject"] = encodeRFC2047(title)
	header["MIME-Version"] = "1.0"
	header["Content-Type"] = "text/plain; 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" + base64.StdEncoding.EncodeToString([]byte(body))

	// Connect to the server, authenticate, set the sender and recipient,
	// and send the email all in one step.
	err := smtp.SendMail(
		smtpServer+smtpPort,
		auth,
		from.Address,
		[]string{to.Address},
		[]byte(message),
		//[]byte("This is the email body."),
	)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 30
0
// Validate a set of supplied user credentials against the JustGiving database
func (svc *Service) Validate(account mail.Address, password string) (valid bool, err error) {

	method := "POST"

	path := bytes.NewBuffer([]byte(svc.BasePath))
	path.WriteString("/")
	path.WriteString(svc.APIKey)
	path.WriteString("/v1/account/validate")

	// mail.Address stores email in the format <*****@*****.**>, we don't want the `<` `>`
	em := account.String()
	em = em[1 : len(em)-1]

	data := struct {
		Email    string
		Password string
	}{em, password}

	sBody, body, err := api.BuildBody("Validate", data, ContentType)
	if err != nil {
		return false, err
	}

	req, err := api.BuildRequest(UserAgent, ContentType, method, path.String(), body)
	if err != nil {
		return false, err
	}

	res, resBody, err := api.Do(svc.client, svc.origin, "Validate", req, sBody, svc.HTTPLogger)
	if err != nil {
		return false, err
	}

	if res.StatusCode != 200 {
		return false, fmt.Errorf("invalid response %s", res.Status)
	}
	var result = struct {
		IsValid bool `json:"isValid"`
	}{}
	if err := json.Unmarshal([]byte(resBody), &result); err != nil {
		return false, fmt.Errorf("invalid response %v", err)
	}
	return result.IsValid, nil

}