示例#1
0
文件: mail.go 项目: no2key/postman
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
}
示例#2
0
文件: justin.go 项目: homemade/justin
// 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

}
示例#3
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)
	}
}
示例#4
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))
}
示例#5
0
文件: justin.go 项目: homemade/justin
// 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
}
示例#6
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, ","))
}
示例#7
0
文件: ses.go 项目: toomore/simpleaws
// 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()),
	}
}
示例#8
0
文件: email.go 项目: 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()
}
示例#9
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?= <*****@*****.**>
}
示例#10
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)
}
示例#11
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

}
示例#12
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
}
示例#13
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
}
示例#14
0
文件: mail.go 项目: hobeone/rss2go
// 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
}
示例#15
0
func InsertHandler(w http.ResponseWriter, r *http.Request) {
	var newSubscriber mail.Address
	newSubscriber.Name = r.FormValue("Name")
	newSubscriber.Address = r.FormValue("Email-id")
	if newSubscriber.Address == "" {
		fmt.Fprintf(w, "Sorry the email field cannot be left empty")
	} else if isPresent(newSubscriber.Address) == true {
		fmt.Fprintf(w, "Sorry the email address is already taken")
	} else {
		AddSubscriber(newSubscriber)
		fmt.Fprintf(w, "You have succesfully subscribed")
	}
}
示例#16
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()
}
示例#17
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()
}
示例#18
0
文件: main.go 项目: uknth/cockpit
func mailer(subject string, content string) bool {
	type Euser struct {
		User   string
		Pass   string
		Server string
		Port   int
	}
	port, _ := strconv.Atoi(val("email", "port"))
	emailUser := &Euser{val("email", "user"), val("email", "password"), val("email", "server"), port}
	auth := smtp.PlainAuth("",
		emailUser.User,
		emailUser.Pass,
		emailUser.Server,
	)
	ml := strings.Split(val("email", "to"), ",")
	for _, val := range ml {
		tos := strings.Split(val, ":")
		from := mail.Address{"Unbxd Monitoring Tool", emailUser.User}
		to := mail.Address{strings.TrimSpace(tos[0]), strings.TrimSpace(tos[1])}
		title := subject
		body := content
		header := make(map[string]string)
		header["From"] = from.String()
		header["To"] = to.String()
		header["Subject"] = func(String string) string {
			// use mail's rfc2047 to encode any string
			addr := mail.Address{String, ""}
			return strings.Trim(addr.String(), " <>")
		}(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(
			emailUser.Server+":"+strconv.Itoa(emailUser.Port),
			auth,
			from.Address,
			[]string{to.Address},
			[]byte(message),
		)
		if err != nil {
			log.Print("Unable to send mail" + err.Error())
		}
	}
	return true
}
示例#19
0
文件: justin.go 项目: homemade/justin
// 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

}
示例#20
0
func SendHtmlMessage(from, to mail.Address, subject, body string) (err error) {
	// Describe the mail headers:
	headers := make(map[string]string)
	headers["From"] = from.String()
	headers["To"] = to.String()
	headers["Subject"] = subject
	headers["Date"] = time.Now().Format(time.RFC1123Z)
	// Use 'text/plain' as an alternative.
	headers["Content-Type"] = `text/html; charset="UTF-8"`

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

	// Deliver email:
	err = smtp.SendMail(Server, nil, from.Address, []string{to.Address}, []byte(message))
	return
}
示例#21
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)
	}
}
示例#22
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)
}
示例#23
0
文件: mail.go 项目: netroby/platform
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
}
示例#24
0
文件: smtp.go 项目: extrame/goblet
func (s *_SmtpSender) sendMail(c client, subject string, mail_body *template.Template, receivers []mail.Address, args map[string]interface{}) (err error) {
	b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

	var standard_header_template *template.Template

	if standard_header_template, err = template.New("standard_header").Parse(StandardHeader); err == nil {
		if err = c.Auth(smtpoverttl.PlainAuth("", *s.User, *s.Pwd, *s.Server)); err == nil {
			for _, receiver := range receivers {
				if err = c.Mail(*s.User); err == nil {
					if err = c.Rcpt(receiver.Address); err == nil {
						// Send the email body.
						var wc io.WriteCloser
						if wc, err = c.Data(); err == nil {
							defer wc.Close()

							from := mail.Address{*s.UserName, *s.User}

							body_writer := new(bytes.Buffer)
							if err = mail_body.Execute(body_writer, args); err != nil {
								return
							}

							if err = standard_header_template.Execute(wc, map[string]string{
								"Receiver": receiver.String(),
								"Sender":   from.String(),
								"Body":     b64.EncodeToString(body_writer.Bytes()),
								"Subject":  fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject))),
							}); err != nil {
								return
							}
						}
					}
				}
			}
		}
	}
	return
}
示例#25
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
}
示例#26
0
文件: justin.go 项目: homemade/justin
// AccountAvailabilityCheck checks the availability of a JustGiving account by email address
func (svc *Service) AccountAvailabilityCheck(account mail.Address) (avail bool, err error) {

	method := "HEAD"

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

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

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

	// 404 is success (available), which is a bit dangerous, so we first make sure we have the correct JustGiving response header
	if res.Header.Get("X-Justgiving-Operation") != "AccountApi:AccountAvailabilityCheck" {
		return false, fmt.Errorf("invalid response, expected X-Justgiving-Operation response header to be AccountApi:AccountAvailabilityCheck but recieved %s", res.Header.Get("X-Justgiving-Operation"))
	}
	if res.StatusCode == 404 {
		return true, nil
	}
	if res.StatusCode != 200 {
		return false, fmt.Errorf("invalid response %s", res.Status)
	}
	// 200 - account exists
	return false, nil

}
示例#27
0
// generate hash, either with email address or OpenID
func (v *Libravatar) genHash(email *mail.Address, openid *url.URL) string {
	if email != nil {
		email.Address = strings.ToLower(strings.TrimSpace(email.Address))
		sum := md5.Sum([]byte(email.Address))
		return fmt.Sprintf("%x", sum)
	} else if openid != nil {
		openid.Scheme = strings.ToLower(openid.Scheme)
		openid.Host = strings.ToLower(openid.Host)
		sum := sha256.Sum256([]byte(openid.String()))
		return fmt.Sprintf("%x", sum)
	}
	// panic, because this should not be reachable
	panic("Neither Email or OpenID set")
}
示例#28
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
}
示例#29
0
文件: smtp.go 项目: WebCivics/gold
// 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")
	}
}
示例#30
0
文件: mail.go 项目: safeie/fserver
// 发送邮件
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
}