Beispiel #1
0
func (self *mailHandler) Perform() error {
	if 0 == len(self.message.To) {
		return nil
	}

	close := func() {
		if len(self.closers) > 0 {
			for _, closer := range self.closers {
				closer.Close()
			}
			self.closers = nil
		}
	}
	defer close()
	var auth smtp.Auth = nil
	if "" != self.password {
		switch self.auth_type {
		case "":
			if 0 != len(self.password) {
				if 0 == len(self.user) {
					self.user = toMailString(&self.message.From)

					if 0 == len(self.user) {
						return errors.New("user is missing.")
					}
				}
				auth = smtp.PlainAuth(self.identity, self.user, self.password, self.host)
			}
		case "plain", "PLAIN":
			if 0 == len(self.user) {
				self.user = toMailString(&self.message.From)
				if 0 == len(self.user) {
					return errors.New("user is missing.")
				}
			}
			if 0 == len(self.host) {
				self.host = self.smtp_server
			}
			auth = smtp.PlainAuth(self.identity, self.user, self.password, self.host)
		case "cram-md5", "CRAM-MD5":
			auth = smtp.CRAMMD5Auth(self.user, self.password)
		default:
			return errors.New("unsupported auth type - " + self.auth_type)
		}
	}
	if e := self.message.Send(self.smtp_server, auth); nil != e {
		return e
	}
	close()

	for _, nm := range self.remove_files {
		if e := os.Remove(nm); nil != e {
			log.Println("[warn] [mail] remove file - '"+nm+"',", e)
		}
	}
	return nil
}
func TestMailMessageTextAndHtml(t *testing.T) {
	if "" == *default_smtp_server {
		t.Skip("please set 'test.mail_to', 'mail.from' and 'mail.smtp_server'")
		return
	}

	msg := &MailMessage{
		From: mail.Address{
			Name:    "发件人的名字",
			Address: *default_mail_address}, // if From.Address is empty, Config.DefaultFrom will be used
		To: []*mail.Address{&mail.Address{
			Name:    "收件人的名字",
			Address: *test_mail_to}},
		Subject:     "这是一个 增 消息",
		ContentText: "这是一个Text消息",
		ContentHtml: `<!doctype html>
		<html lang="en">
		 <head>
		  <meta charset="UTF-8">
		  <title>test</title>
		 </head>
		 <body>
		  这是一个 Html 消息
		 </body>
		</html>
		`,
		Attachments: []Attachment{
			{Name: "中文名的附件.txt", Content: strings.NewReader("aaaaaoooo")},
		}}

	// bs, e := msg.Bytes()
	// if nil != e {
	// 	t.Error(e)
	// 	return
	// }
	// t.Log(string(bs))

	if e := msg.Send(*default_smtp_server, smtp.PlainAuth(*default_mail_auth_identity,
		*default_mail_address,
		*default_mail_auth_password,
		*default_mail_auth_host)); nil != e {
		t.Error(e)
	}
}