本文整理汇总了Golang中net/smtp.Client.Auth方法的典型用法代码示例。如果您正苦于以下问题:Golang Client.Auth方法的具体用法?Golang Client.Auth怎么用?Golang Client.Auth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/smtp.Client
的用法示例。
在下文中一共展示了Client.Auth方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: smtpSendMailPart2
func smtpSendMailPart2(c *smtp.Client, smtpHost string, a smtp.Auth, from string, to []string, msg []byte) (err error) {
defer c.Close()
if err = c.Hello("localhost"); err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
config := &tls.Config{ServerName: smtpHost}
if err = c.StartTLS(config); 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
}
}
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()
}
示例2: Send
func (DefaultSender) Send(from, to, content string) error {
var (
err error
c *smtp.Client
auth smtp.Auth
)
log.Println("mail: sending mail to " + to)
auth, err = DefaultSender{}.auth()
if nil != err {
return err
}
c, err = smtp.Dial(MAIL_HOST + ":" + MAIL_PORT)
if nil != err {
return err
}
defer c.Close()
tlc := &tls.Config{
InsecureSkipVerify: true,
ServerName: MAIL_HOST,
}
if err = c.StartTLS(tlc); err != nil {
log.Println("tls error " + err.Error())
return err
}
c.Auth(auth)
c.Mail(from)
c.Rcpt(to)
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
buf := bytes.NewBufferString(content)
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
if err != nil {
log.Println("email: failed to write " + err.Error())
return err
}
return err
}
示例3: NewSmtpClient
func NewSmtpClient(addr string, a smtp.Auth, concurrency int) (client *SmtpClient, err error) {
pool := make(chan *smtp.Client, concurrency)
for i := 0; i < concurrency; i++ {
var c *smtp.Client
c, err = smtp.Dial(addr)
if err != nil {
return
}
if err = c.Hello("localhost"); err != nil {
return
}
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(nil); err != nil {
return
}
}
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return
}
}
pool <- c
}
client = &SmtpClient{pool, &sync.Mutex{}, false}
return
}
示例4: sendEmail
func sendEmail(templ, subject, username, toUser, tokenVerify, text, cmd, device string) error {
t := template.New("Email template")
t, err := t.Parse(templ)
if err != nil {
log.Errorf("Error with parsing template:%s ", err.Error())
return err
}
paramEmail := ¶mEmail{
TextVerify: text,
CMDVerify: cmd,
}
var b bytes.Buffer
err = t.Execute(&b, paramEmail)
if err != nil {
log.Errorf("Error with Execute template:%s ", err.Error())
return err
}
if viper.GetBool("no_smtp") {
fmt.Println("##### NO SMTP DISPLAY MAIL IN CONSOLE ######")
fmt.Printf("Subject:%s\n", subject)
fmt.Printf("Text:%s\n", b.Bytes())
fmt.Println("##### END MAIL ######")
return nil
}
from := mail.Address{
Name: "",
Address: viper.GetString("smtp_from"),
}
to := mail.Address{
Name: "",
Address: toUser,
}
// Setup headers
headers := make(map[string]string)
headers["From"] = viper.GetString("smtp_from")
headers["To"] = to.String()
headers["Subject"] = subject
// Setup message
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + b.String()
// Connect to the SMTP Server
servername := fmt.Sprintf("%s:%s", viper.GetString("smtp_host"), viper.GetString("smtp_port"))
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: viper.GetString("smtp_host"),
}
var c *smtp.Client
if viper.GetBool("smtp_tls") {
// 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)
conn, errc := tls.Dial("tcp", servername, tlsconfig)
if errc != nil {
log.Errorf("Error with c.Dial:%s", errc.Error())
return err
}
c, err = smtp.NewClient(conn, viper.GetString("smtp_host"))
if err != nil {
log.Errorf("Error with c.NewClient:%s", err.Error())
return err
}
} else {
c, err = smtp.Dial(servername)
if err != nil {
log.Errorf("Error while smtp.Dial:%s", err)
}
defer c.Close()
}
// Auth
if viper.GetString("smtp_user") != "" && viper.GetString("smtp_password") != "" {
auth := smtp.PlainAuth("", viper.GetString("smtp_user"), viper.GetString("smtp_password"), viper.GetString("smtp_host"))
if err = c.Auth(auth); err != nil {
log.Errorf("Error with c.Auth:%s", err.Error())
return err
}
}
// To && From
if err = c.Mail(from.Address); err != nil {
log.Errorf("Error with c.Mail:%s", err.Error())
return err
}
//.........这里部分代码省略.........
示例5: Deliver
func (es *EmailDeliverer) Deliver(alertCtx AlertContext, alertConf model.AlertConfig) error {
rcptRaw, ok := alertConf.Settings["recipient"]
if !ok {
return fmt.Errorf("missing email address")
}
evergreen.Logger.Logf(slogger.INFO, "Sending email to %v", rcptRaw)
var rcpt string
if rcpt, ok = rcptRaw.(string); !ok {
return fmt.Errorf("email address must be a string")
}
var err error
subject := getSubject(alertCtx)
body, err := es.getBody(alertCtx)
if err != nil {
return err
}
var c *smtp.Client
if es.UseSSL {
tlsCon, err := tls.Dial("tcp", fmt.Sprintf("%v:%v", es.Server, es.Port), &tls.Config{})
if err != nil {
return err
}
c, err = smtp.NewClient(tlsCon, es.Server)
} else {
c, err = smtp.Dial(fmt.Sprintf("%v:%v", es.Server, es.Port))
}
if err != nil {
return err
}
if es.Username != "" {
err = c.Auth(smtp.PlainAuth("", es.Username, es.Password, es.Server))
if err != nil {
return err
}
}
// Set the sender
from := mail.Address{"Evergreen Alerts", es.From}
err = c.Mail(es.From)
if err != nil {
evergreen.Logger.Errorf(slogger.ERROR, "Error establishing mail sender (%v): %v", es.From, err)
return err
}
err = c.Rcpt(rcpt)
if err != nil {
evergreen.Logger.Errorf(slogger.ERROR, "Error establishing mail recipient (%v): %v", rcpt, err)
return err
}
// Send the email body.
wc, err := c.Data()
if err != nil {
return err
}
defer wc.Close()
// set header information
header := make(map[string]string)
header["From"] = from.String()
header["To"] = rcpt
header["Subject"] = encodeRFC2047(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" + base64.StdEncoding.EncodeToString([]byte(body))
// write the body
buf := bytes.NewBufferString(message)
if _, err = buf.WriteTo(wc); err != nil {
return err
}
return nil
}
示例6: SendMailMessage
// SendMailMessage handles outgoing message to SMTP server.
//
// - The connections to the service can be either plain (port 25)
// or SSL/TLS (port 465)
//
// - If the server supports STARTTLS and the channel is not already
// encrypted (via SSL), the application will use the "STLS" command
// to initiate a channel encryption.
//
// - Connections can be tunneled through any SOCKS5 proxy (like Tor)
func SendMailMessage(host, proxy, fromAddr, toAddr string, body []byte) error {
var (
c0 net.Conn
c1 *tls.Conn
cli *smtp.Client
)
defer func() {
if cli != nil {
cli.Close()
}
if c1 != nil {
c1.Close()
}
if c0 != nil {
c0.Close()
}
}()
uSrv, err := url.Parse(host)
if err != nil {
return err
}
if proxy == "" {
c0, err = net.Dial("tcp", uSrv.Host)
} else {
host, port, err := SplitHost(uSrv.Host)
if err != nil {
return err
}
c0, err = Socks5Connect("tcp", host, port, proxy)
}
if err != nil {
return err
}
if c0 == nil {
return errors.New("Can't estabish connection to " + uSrv.Host)
}
sslConfig := &tls.Config{InsecureSkipVerify: true}
if uSrv.Scheme == "smtps" {
c1 = tls.Client(c0, sslConfig)
if err = c1.Handshake(); err != nil {
return err
}
cli, err = smtp.NewClient(c1, uSrv.Host)
} else {
cli, err = smtp.NewClient(c0, uSrv.Host)
if err == nil {
if ok, _ := cli.Extension("STLS"); ok {
err = cli.StartTLS(sslConfig)
}
}
}
if err != nil {
return err
}
pw, _ := uSrv.User.Password()
auth := smtp.PlainAuth("", uSrv.User.Username(), pw, uSrv.Host)
if err = cli.Auth(auth); err != nil {
return err
}
if err = cli.Mail(fromAddr); err != nil {
return err
}
if err = cli.Rcpt(toAddr); err != nil {
return err
}
wrt, err := cli.Data()
if err != nil {
return err
}
wrt.Write(body)
wrt.Close()
if err = cli.Quit(); err != nil {
return err
}
return nil
}
示例7: SendMail
/* Connects an SMTP server (usually localhost:25 in prod) and uses that to
send an email with the body encoded in base64. */
func (self SmtpMailer) SendMail(recipients []string, subject, body string) error {
// 'recipients' is expected a comma-separated list of emails in either of
// these formats:
// - [email protected]
// - Bob Smith <[email protected]>
var c *smtp.Client
var err error
if self.UseSSL {
tlsCon, err := tls.Dial("tcp", fmt.Sprintf("%v:%v", self.Server, self.Port), &tls.Config{})
if err != nil {
return err
}
c, err = smtp.NewClient(tlsCon, self.Server)
} else {
c, err = smtp.Dial(fmt.Sprintf("%v:%v", self.Server, self.Port))
}
if err != nil {
return err
}
if self.Username != "" {
err = c.Auth(smtp.PlainAuth("", self.Username, self.Password, self.Server))
if err != nil {
return err
}
}
// Set the sender
from := mail.Address{"Evergreen Alerts", self.From}
err = c.Mail(self.From)
if err != nil {
evergreen.Logger.Errorf(slogger.ERROR, "Error establishing mail sender (%v): %v", self.From, err)
return err
}
// Set the recipient
for _, recipient := range recipients {
err = c.Rcpt(recipient)
if err != nil {
evergreen.Logger.Errorf(slogger.ERROR, "Error establishing mail recipient (%v): %v", recipient, err)
return err
}
}
// Send the email body.
wc, err := c.Data()
if err != nil {
return err
}
defer wc.Close()
// set header information
header := make(map[string]string)
header["From"] = from.String()
header["To"] = strings.Join(recipients, ", ")
header["Subject"] = encodeRFC2047(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" + base64.StdEncoding.EncodeToString([]byte(body))
// write the body
buf := bytes.NewBufferString(message)
if _, err = buf.WriteTo(wc); err != nil {
return err
}
return nil
}
示例8: SendWithHELO
// Send an email using the given host, SMTP auth (optional) and HELO hostname, 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) SendWithHELO(hostname string, port int32, a smtp.Auth, heloHostname string, esCerts *configprofile.CodeSigningCerts) error {
// format server address
addr := fmt.Sprintf("%s:%d", hostname, port)
// 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
}
// Sign the email with S/MIME
cmd := exec.Command("openssl", "smime", "-sign", "-signer", esCerts.Cert, "-inkey", esCerts.Key)
emailBytes, err := e.Bytes()
if err != nil {
return err
}
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
stdin.Write(emailBytes)
stdin.Close()
signedData, err := ioutil.ReadAll(stdout)
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
return err
}
var signedEmail bytes.Buffer
headerToBytes(&signedEmail, e.msgHeaders())
signedEmail.Write(signedData)
raw := signedEmail.Bytes()
// Manually send email using net/smtp
var c *smtp.Client
if port == 465 {
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: hostname,
}
// 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)
conn, err := tls.Dial("tcp", addr, tlsconfig)
if err != nil {
return err
}
c, err = smtp.NewClient(conn, hostname)
if err != nil {
return err
}
} else {
c, err = smtp.Dial(addr)
if err != nil {
return err
}
}
defer c.Close()
if err = c.Hello(heloHostname); err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
config := &tls.Config{ServerName: hostname}
if err = c.StartTLS(config); err != nil {
return err
}
//.........这里部分代码省略.........