Example #1
0
func TestTimeout(t *testing.T) {
	s, err := NewServer(&Config{
		Addr:        "127.0.0.1:0",
		ReadTimeout: 50 * time.Millisecond,
	})
	if err != nil {
		t.Fatal(err)
	}
	// Connect to the server using its address
	conn, err := net.Dial("tcp", s.listener.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	c, err := smtp.NewClient(conn, "localhost")
	if err != nil {
		t.Fatal(err)
	}
	// Hang for 100ms to trigger the timeout
	time.Sleep(100 * time.Millisecond)
	conn.SetDeadline(time.Now().Add(100 * time.Millisecond))
	if err := c.Hello("localhost"); err == nil {
		t.Fatal(errors.New("timeout expected"))
	}
	s.Close(false)
}
Example #2
0
func sendMail(t *testing.T, unixSocket, testData string) {
	conn, err := net.Dial("unix", unixSocket)
	if err != nil {
		t.Error(err)
	}

	c, err := smtp.NewClient(conn, "localhost")
	defer c.Quit()

	if err != nil {
		t.Error(err)
	}

	c.Mail("ignored")
	c.Rcpt("ignored")

	w, err := c.Data()
	defer w.Close()
	if err != nil {
		t.Error(err)
	}

	data, err := ioutil.ReadFile(testData)
	if err != nil {
		t.Error(err)
	}

	w.Write(data)
}
Example #3
0
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
}
Example #4
0
// Send the given email messages using this Mailer.
func (m *Mailer) SendTestMessage(basicServer string, messages ...*Message) (actualcmds string, err error) {
	if m.Auth == nil {
		m.Auth = smtp.PlainAuth(m.UserName, m.UserName, m.Password, m.Server)
	}

	server := strings.Join(strings.Split(basicServer, "\n"), "\r\n")
	var cmdbuf bytes.Buffer
	bcmdbuf := bufio.NewWriter(&cmdbuf)
	var fake faker
	fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)

	defer func() {
		bcmdbuf.Flush()
		actualcmds = cmdbuf.String()
	}()

	c, err := smtp.NewClient(fake, "fake.host")
	if err != nil {
		return
	}
	defer c.Quit()

	for _, message := range messages {
		m.fillDefault(message)
		if err = Send(c, message); err != nil {
			return
		}
	}

	return
}
Example #5
0
func newSMTPClient(conn net.Conn) (*smtp.Client, *model.AppError) {
	host, _, _ := net.SplitHostPort(Cfg.EmailSettings.SMTPServer)
	c, err := smtp.NewClient(conn, host)
	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("", Cfg.EmailSettings.SMTPUsername, Cfg.EmailSettings.SMTPPassword, host)
	if Cfg.EmailSettings.UseTLS {
		if err = c.Auth(auth); err != nil {
			return nil, model.NewAppError("SendMail", "Failed to authenticate on SMTP server", err.Error())
		}
	} else if Cfg.EmailSettings.UseStartTLS {
		tlsconfig := &tls.Config{
			InsecureSkipVerify: true,
			ServerName:         host,
		}
		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
}
Example #6
0
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(T("utils.mail.new_client.open.error"), err)
		return nil, model.NewLocAppError("SendMail", "utils.mail.connect_smtp.open_tls.app_error", nil, err.Error())
	}
	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.NewLocAppError("SendMail", "utils.mail.new_client.auth.app_error", nil, 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.NewLocAppError("SendMail", "utils.mail.new_client.auth.app_error", nil, err.Error())
		}
	} else if config.EmailSettings.ConnectionSecurity == model.CONN_SECURITY_PLAIN {
		// note: go library only supports PLAIN auth over non-tls connections
		if err = c.Auth(auth); err != nil {
			return nil, model.NewLocAppError("SendMail", "utils.mail.new_client.auth.app_error", nil, err.Error())
		}
	}
	return c, nil
}
Example #7
0
// dial connects to the smtp server with the request encryption type
func dial(host string, port string, encryption encryption, config *tls.Config) (*smtp.Client, error) {
	var conn net.Conn
	var err error

	address := host + ":" + port

	// do the actual dial
	switch encryption {
	case EncryptionSSL:
		conn, err = tls.Dial("tcp", address, config)
	default:
		conn, err = net.Dial("tcp", address)
	}

	if err != nil {
		return nil, errors.New("Mail Error on dailing with encryption type " + encryption.String() + ": " + err.Error())
	}

	c, err := smtp.NewClient(conn, host)

	if err != nil {
		return nil, errors.New("Mail Error on smtp dial: " + err.Error())
	}

	return c, err
}
Example #8
0
func (e *EmailAlerter) SendAlert(errors map[string][]string) error {
	log.Println("dialing:", e.Smtp)

	conn, err := net.DialTimeout("tcp", e.Smtp, 15*time.Second)
	if err != nil {
		return err
	}
	defer conn.Close()

	c, err := smtp.NewClient(conn, e.Smtp)
	if err != nil {
		return err
	}
	defer c.Close()

	c.Mail(e.From)
	c.Rcpt(e.To)

	wc, err := c.Data()
	if err != nil {
		return err
	}
	defer wc.Close()

	buf := bytes.NewBufferString(fmt.Sprintf("%v", errors))
	if _, err = buf.WriteTo(wc); err != nil {
		return err
	}

	return nil
}
Example #9
0
func Dial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil) //smtp包中net.Dial()当使用ssl连接时会卡住
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}
Example #10
0
//return a smtp client
func Dial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil)
	if err != nil {
		log.Println("Dialing Error:", err)
		return nil, err
	}
	//分解主机端口字符串
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}
Example #11
0
// SSL方式连接服务器 (与STARTTLS方式不同 适用于465端口)
func (this *SMTPClient) sendSSL(to []string, title, context string) (err error) {
	defer util.Catch(&err)
	host := this.Server[:strings.Index(this.Server, ":")]
	conn, err := tls.Dial("tcp", this.Server, nil)
	if err != nil {
		return err
	}
	c, err := smtp.NewClient(conn, host)
	if err != nil {
		return err
	}
	*(*bool)(unsafe.Pointer(reflect.ValueOf(c).Elem().FieldByName("tls").UnsafeAddr())) = true // set tls to true for AUTH

	if this.auth != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(this.auth); err != nil {
				return err
			}
		}
	}
	if err = c.Mail(this.User); err != nil {
		return err
	}
	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}
	body := []byte(strings.Join([]string{
		"From: " + this.User,
		"To: " + strings.Join(to, ","),
		"Subject: " + title,
		"Content-Type: text/html; charset=utf-8;",
		"",
		context,
	}, "\r\n"))
	_, err = w.Write(body)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	return c.Quit()
}
Example #12
0
// sendMail connects to the server at addr, switches to TLS if possible (using the given config),
// authenticates with mechanism a if possible, and then sends an email from
// address from, to addresses to, with message msg.
//
// If msg is nil, then quits, this testing the recipients and the server
func sendMail(addr string, a smtp.Auth, from string, to []string, msg []byte, timeout time.Duration, tlsConfig *tls.Config) error {
	//c, err := Dial(addr)
	conn, err := net.DialTimeout("tcp", addr, timeout)
	if err != nil {
		return err
	}
	host, _, _ := net.SplitHostPort(addr)
	c, err := smtp.NewClient(conn, host)
	if err != nil {
		return err
	}
	//if err := c.hello(); err != nil {
	//    return err
	//}
	if err := c.Hello("localhost"); err != nil {
		return err
	}
	if ok, _ := c.Extension("STARTTLS"); ok {
		if err = c.StartTLS(tlsConfig); err != nil {
			return err
		}
	}
	if a != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(a); err != nil {
				return err
			}
		}
	}
	if err = c.Mail(from); err != nil {
		return err
	}
	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return err
		}
	}
	if msg != nil {
		w, err := c.Data()
		if err != nil {
			return err
		}
		_, err = w.Write(msg)
		if err != nil {
			return err
		}
		err = w.Close()
		if err != nil {
			return err
		}
	}
	return c.Quit()
}
Example #13
0
// copy & past https://gist.github.com/chrisgillis/10888032
func send_digest(smtp_conn smtp_conn_type, msg []byte) error {
	servername := strings.Join([]string{smtp_conn.Host, smtp_conn.Port}, ":")

	auth := smtp.PlainAuth("", smtp_conn.Login, smtp_conn.Password, smtp_conn.Host)

	// TLS config
	tlsconfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         smtp_conn.Host,
	}

	conn, err := tls.Dial("tcp", ""+servername, tlsconfig)
	if err != nil {
		return err
	}

	c, err := smtp.NewClient(conn, smtp_conn.Host)
	if err != nil {
		return err
	}

	if err = c.Auth(auth); err != nil {
		return err
	}

	if err = c.Mail(smtp_conn.Login); err != nil {
		return err
	}

	if err = c.Rcpt(email); err != nil {
		return err
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(msg)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	c.Quit()

	return nil
}
Example #14
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()
}
Example #15
0
// SendMailSSL envoie un email par SSL
func SendMailSSL(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
	conn, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) //TODO: Not secure
	if err != nil {
		log.Println("Error Dialing", err)
		return err
	}
	h, _, _ := net.SplitHostPort(addr)
	c, err := smtp.NewClient(conn, h)
	if err != nil {
		log.Println("Error SMTP connection", err)
		return err
	}
	defer c.Close()

	if a != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(a); err != nil {
				return err
			}
		}
	}

	if err = c.Mail(from); err != nil {
		return err
	}

	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(msg)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	return c.Quit()
}
Example #16
0
//Send should validate and send mail.
func (m *Mail) Send() {
	//Setup Headers
	message := makeHeaders(m) + m.Body.Build() + m.Attachment.Build()

	host, _, _ := net.SplitHostPort(m.Conf.ServerName)
	tlsconfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         host,
	}

	conn, err := tls.Dial("tcp", m.Conf.ServerName, tlsconfig)
	if err != nil {
		log.Panic(err)
	}

	c, err := smtp.NewClient(conn, host)
	if err != nil {
		log.Panic(err)
	}

	if err = c.Auth(smtp.PlainAuth("", m.Conf.From, m.Conf.Password, host)); err != nil {
		log.Panic(err)
	}

	if err = c.Mail(m.Conf.From); err != nil {
		log.Panic(err)
	}

	if err = c.Rcpt(m.Conf.To); err != nil {
		log.Panic(err)
	}

	w, err := c.Data()
	if err != nil {
		log.Panic(err)
	}

	_, err = w.Write([]byte(message))
	if err != nil {
		log.Panic(err)
	}

	err = w.Close()
	if err != nil {
		log.Panic(err)
	}

	c.Quit()
}
// Here is the key, you need to call tls.Dial instead of smtp.Dial
// for smtp servers running on 465 that require an ssl connection
// from the very beginning (no starttls)
func doRawTLSConn(servername string, tlsconfig *tls.Config, auth smtp.Auth, from mail.Address, to mail.Address, message string) {

	host, _, _ := net.SplitHostPort(servername)

	conn, err := tls.Dial("tcp", servername, tlsconfig)
	if err != nil {
		log.Panic(err)
	}

	c, err := smtp.NewClient(conn, host)
	if err != nil {
		log.Panic(err)
	}

	// Auth
	if err = c.Auth(auth); err != nil {
		log.Panic(err)
	}

	// To && From
	if err = c.Mail(from.Address); err != nil {
		log.Panic(err)
	}

	if err = c.Rcpt(to.Address); err != nil {
		log.Panic(err)
	}

	// Data
	w, err := c.Data()
	if err != nil {
		log.Panic(err)
	}

	_, err = w.Write([]byte(message))
	if err != nil {
		log.Panic(err)
	}

	err = w.Close()
	if err != nil {
		log.Panic(err)
	}

	c.Quit()
}
Example #18
0
//Proxy handles a proxy operation
func (s SMTPProxyConn) Proxy( /*c *ProxyConfig*/ ) error {
	// if notready {
	// 	return ErrBadSMTP
	// }

	addr, _, _ := net.SplitHostPort(s.TargetConn.RemoteAddr().String())
	client, err := smtp.NewClient(s.TargetConn, addr)

	if err != nil {
		return err
	}

	_ = client

	config := s.c
	config.Conn = s.Conn

	session := NewSMTPSession(&config, s.TargetConn)

	//close the session
	defer session.Close()

	//lets start proxy the commands between the clients
	for rec := range session.Serve() {
		// _ = cmd

		cmd := rec.Cmd
		log.Debug("Cmd: %s, Fields: %s Data: %s Line: %s", cmd.Action, cmd.Fields, cmd.Params, cmd.Packet)

		// the plan is to recieve our Commands(cmd) then take the data
		//and send that to our the client that delivers that to the smtp Server
		//on the container ,take the response and record then send that back to the
		//requester

		err := smtpHandlers(&rec, client, session)
		log.Error("Handling SMTP Request %s", cmd.Action, err)

		if err != nil {
			session.Reply(502, fmt.Sprintf("Request %s Failed for proxy", cmd.Action))
		}

		close(rec.Finished)
	}

	return nil
}
Example #19
0
func SendMail(to []string, subject, body string) (err error) {
	if addr == "" {
		// skip if not configured
		return nil
	}
	// create client
	var conn net.Conn
	var client *smtp.Client
	if conn, err = net.Dial("tcp", addr+":25"); err != nil {
		return logError(err, to, subject, body)
	}
	if client, err = smtp.NewClient(conn, ""); err != nil {
		return logError(err, to, subject, body)
	}
	defer client.Quit()
	msg := fmt.Sprintf("From: %s\n", from)
	if err = client.Mail(from); err != nil {
		return logError(err, to, subject, body)
	}
	for _, addr := range to {
		msg += fmt.Sprintf("To: %s\n", addr)
		if err = client.Rcpt(addr); err != nil {
			return logError(err, to, subject, body)
		}
	}
	for _, addr := range cc {
		msg += fmt.Sprintf("Cc: %s\n", addr)
		if err = client.Rcpt(addr); err != nil {
			return logError(err, to, subject, body)
		}
	}
	msg += fmt.Sprintf("Date: %s\n", time.Now().String())
	msg += fmt.Sprintf("Subject: %s\n\n", subject)
	msg += body

	w, err := client.Data()
	if err != nil {
		return logError(err, to, subject, body)
	}

	fmt.Fprintf(w, msg)
	w.Close()
	log.Printf("[SMTP] SENT: %v '%s'", to, subject)
	return nil
}
Example #20
0
func sendMailWithTLS(m Mail, auth smtp.Auth, content []byte) error {
	conn, err := tls.Dial("tcp", mc.Host+":"+mc.Port, nil)
	if err != nil {
		return err
	}

	client, err := smtp.NewClient(conn, mc.Host)
	if err != nil {
		return err
	}
	defer client.Close()

	if ok, _ := client.Extension("AUTH"); ok {
		if err = client.Auth(auth); err != nil {
			return err
		}
	}

	if err = client.Mail(m.From); err != nil {
		return err
	}

	for _, to := range m.To {
		if err = client.Rcpt(to); err != nil {
			return err
		}
	}

	w, err := client.Data()
	if err != nil {
		return err
	}

	_, err = w.Write(content)
	if err != nil {
		return err
	}

	err = w.Close()
	if err != nil {
		return err
	}

	return client.Quit()
}
Example #21
0
func sendMail(subject string, body []byte, to []string) error {
	auth := smtp.PlainAuth("", from, pass, smtpHost)

	conn, err := tls.Dial("tcp", smtpHost+":465", nil)
	if err != nil {
		return err
	}
	client, err := smtp.NewClient(conn, smtpHost)
	if err != nil {
		return err
	}
	if err = client.Auth(auth); err != nil {
		return err
	}
	if err = client.Mail(from); err != nil {
		return err
	}

	contentType := "Content-Type:text/plain;charset=UTF-8"
	var msg []byte
	str := fmt.Sprint(
		"To:", strings.Join(to, ";"),
		"\r\nFrom:", from,
		"\r\nSubject:", subject,
		"\r\n", contentType,
		"\r\n\r\n",
	)
	msg = append(msg, str...)
	msg = append(msg, body...)
	for _, addr := range to {
		if err := client.Rcpt(addr); err != nil {
			return err
		}
	}
	writer, err := client.Data()
	if err != nil {
		return err
	}
	_, err = writer.Write(msg)
	if err != nil {
		return err
	}
	writer.Close()
	return nil
}
Example #22
0
// TLSSend makes the initial connection as TLS and starts the smtp conversation, this should be used with port 465. smtp.SendMail connects and sends HELO in the clear first and then upgrades to TLS if allowed or errors out.
func TLSSend(sc ServerConfig, emailFromOverride string, emailTo []string, body []byte) (err error) {

	addrport := fmt.Sprintf("%s:%d", sc.Host, sc.Port)

	var vo x509.VerifyOptions
	//vo.Roots = getRootCAs()

	verifyCert(vo)

	tlsConf := new(tls.Config)
	tlsConf.RootCAs = vo.Roots

	conn, err := tls.Dial("tcp", addrport, tlsConf)
	if err != nil {
		fmt.Printf("Dial error: %s", err)
		return err
	}

	smtpClient, err := smtp.NewClient(conn, "")
	if err != nil {
		fmt.Printf("NewClient err: %s", err)
		return err
	}

	from := emailFromOverride
	if from == "" {
		from = sc.EmailFrom
	}

	err = smtpClient.Hello("localhost")
	if err != nil {
		fmt.Printf("smtp Hello err: %s", err)
		return err
	}

	//auth := smtp.PlainAuth("", sc.User, sc.Password, sc.Host)

	// bug(Grant) finish the dialog
	panic("implementation of TLSSend not complete")

	return nil
}
Example #23
0
File: smtp.go Project: Xuyuanp/logo
// connect connects to SMTP server, init the client and init buffer.
func (sw *SMTPWriter) connect() error {
	// init client
	conn, err := tls.Dial("tcp", sw.addr, nil)
	if err != nil {
		return err
	}
	host, _, err := net.SplitHostPort(sw.addr)
	if err != nil {
		return err
	}
	c, err := smtp.NewClient(conn, host)
	if err != nil {
		return err
	}
	auth := smtp.PlainAuth("", sw.username, sw.password, host)
	if err := c.Auth(auth); err != nil {
		return err
	}
	if err := c.Mail(sw.username); err != nil {
		return err
	}
	sw.cli = c

	// init SMTP header
	header := map[string]string{
		"From":         sw.username,
		"To":           strings.Join(sw.to, ";"),
		"Subject":      sw.subject,
		"MIME-Version": "1.0",
		"Content-Type": `text/plain; charset="utf-8"`,
	}
	var buf []byte
	for k, v := range header {
		buf = append(buf, k...)
		buf = append(buf, ':', ' ')
		buf = append(buf, v...)
		buf = append(buf, '\r', '\n')
	}
	buf = append(buf, "\r\n\r\n"...)
	sw.buf = buf
	return nil
}
Example #24
0
File: agent.go Project: gbbr/gomez
func (cron *cronJob) getSMTPClient(host string) (*smtp.Client, error) {
	MXs, err := lookupMX(host)
	if err != nil {
		return nil, err
	}
	for retry := 0; retry < 2; retry++ {
		for _, mx := range MXs {
			conn, err := net.DialTimeout("tcp", mx.Host+":25", 5*time.Second)
			if err != nil {
				continue
			}
			client, err := smtp.NewClient(conn, "mecca.local")
			if err != nil {
				continue
			}
			return client, nil
		}
	}
	return nil, errFailedHost
}
Example #25
0
func doSMTP(s *shim, conf *tls.Config) error {
	c, err := smtp.NewClient(s, conf.ServerName)
	if err != nil {
		return fmt.Errorf("smtp new client failed: %s", err)
		return err
	}
	if ok, _ := c.Extension("STARTTLS"); !ok {
		return fmt.Errorf("smtp server does not support starttls")
	}
	s.Start()
	err = c.StartTLS(conf)
	s.Stop()
	if err != nil {
		return fmt.Errorf("smtp starttls failed: %s", err)
	}
	if err := c.Quit(); err != nil {
		return fmt.Errorf("smtp quit failed: %s", err)
	}
	return nil
}
Example #26
0
// Transport initialize the smtp client
func Transport(address string, port int, host string, a smtp.Auth) (*smtp.Client, error) {
	addr := fmt.Sprintf("%s:%d", address, port)

	var conn net.Conn
	conn, err := tls.Dial("tcp", addr, nil) // some smtp servers require TLS handshake
	if err != nil {
		conn, err = net.Dial("tcp", addr) // fall back
		if err != nil {
			return nil, err
		}
	}

	c, err := smtp.NewClient(conn, address)
	if err != nil {
		return nil, err
	}

	if host != "" {
		if err := c.Hello(host); err != nil {
			return nil, err
		}
	}

	if ok, _ := c.Extension("STARTTLS"); ok {
		config := &tls.Config{
			InsecureSkipVerify: true,
		}

		if err = c.StartTLS(config); err != nil {
			return nil, err
		}
	}
	if a != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(a); err != nil {
				return nil, err
			}
		}
	}
	return c, nil
}
Example #27
0
func Fuzz(data []byte) int {
	conn := &MyConn{data, false, false}
	defer func() {
		if !conn.closed {
			panic("connection is not closed")
		}
	}()
	c, err := smtp.NewClient(conn, "golang.org")
	if err != nil {
		return 0
	}
	defer c.Close()
	if err = c.Hello("localhost"); err != nil {
		return 0
	}
	if err = c.Auth(smtp.PlainAuth("identiry", "username", "password", "host")); err != nil {
		return 1
	}
	if err = c.Mail("*****@*****.**"); err != nil {
		return 1
	}
	if err = c.Rcpt("*****@*****.**"); err != nil {
		return 1
	}
	w, err := c.Data()
	if err != nil {
		return 1
	}
	_, err = w.Write([]byte("message"))
	if err != nil {
		return 1
	}
	if err = w.Close(); err != nil {
		return 1
	}
	if err = c.Quit(); err != nil {
		return 1
	}
	return 2
}
Example #28
0
func SmtpSendEmail(req *SmtpRequest) (err error) {
	parameters := &struct {
		From    string
		To      string
		Subject string
		Message string
	}{
		req.From,
		strings.Join([]string(req.To), ","),
		req.Subject,
		req.Message,
	}
	buffer := new(bytes.Buffer)
	t := template.Must(template.New("emailTemplate").Parse(_EmailScript()))
	t.Execute(buffer, parameters)
	auth := smtp.PlainAuth("", req.From, req.SmtpPassword, req.SmtpHost)
	var conn net.Conn
	if req.Socks4aProxyAddr != "" {
		conn, err = kmgProxy.Socks4aDial(req.Socks4aProxyAddr, kmgNet.JoinHostPortInt(req.SmtpHost, req.SmtpPort))
	} else {
		conn, err = net.Dial("tcp", kmgNet.JoinHostPortInt(req.SmtpHost, req.SmtpPort))
	}
	if err != nil {
		kmgLog.Log("Email", "1", err.Error())
		return
	}
	c, err := smtp.NewClient(conn, req.SmtpHost)
	if err != nil {
		kmgLog.Log("Email", err.Error())
		return
	}
	err = smtpSendMailPart2(c,
		req.SmtpHost,
		auth,
		req.From,
		req.To,
		buffer.Bytes())
	return err
}
Example #29
0
func (di *dialerImpl) Dial() (smtpClient, error) {
	hostport := net.JoinHostPort(di.server, di.port)
	var conn net.Conn
	var err error
	// By convention, port 465 is TLS-wrapped SMTP, while 587 is plaintext SMTP
	// (with STARTTLS as best-effort).
	if di.port == "465" {
		conn, err = tls.Dial("tcp", hostport, nil)
	} else {
		conn, err = net.Dial("tcp", hostport)
	}
	if err != nil {
		return nil, err
	}
	client, err := smtp.NewClient(conn, di.server)
	if err != nil {
		return nil, err
	}
	auth := smtp.PlainAuth("", di.username, di.password, di.server)
	if err = client.Auth(auth); err != nil {
		return nil, err
	}
	return client, nil
}
Example #30
0
// Connect opens a connection to the specified mail server. It must be called
// before SendMail.
func (m *MailerImpl) Connect() error {
	hostport := net.JoinHostPort(m.server, m.port)
	var conn net.Conn
	var err error
	// By convention, port 465 is TLS-wrapped SMTP, while 587 is plaintext SMTP
	// (with STARTTLS as best-effort).
	if m.port == "465" {
		conn, err = tls.Dial("tcp", hostport, nil)
	} else {
		conn, err = net.Dial("tcp", hostport)
	}
	if err != nil {
		return err
	}
	client, err := smtp.NewClient(conn, m.server)
	if err != nil {
		return err
	}
	if err = client.Auth(m.auth); err != nil {
		return err
	}
	m.client = client
	return nil
}