2012-06-16 33 views
1

發送電子郵件我有不使用加密連接的SMTP帳戶。我可以使用相同的帳戶發送從C#和Python的電子郵件沒有問題,但與去我得到的錯誤: 未加密的連接通過未加密的連接

這是我使用的代碼:

package main 

import (
     "log" 
     "net/smtp" 
) 

func main() { 
     // Set up authentication information. 
     auth := smtp.PlainAuth(
       "", 
       "[email protected]", 
       "password", 
       "mail.example.com", 
     ) 
     // Connect to the server, authenticate, set the sender and recipient, 
     // and send the email all in one step. 
     err := smtp.SendMail(
       "mail.example.com:25", 
       auth, 
       "[email protected]", 
       []string{"[email protected]"}, 
       []byte("This is the email body."), 
     ) 
     if err != nil { 
       log.Fatal(err) 
     } 
} 

回答

7

這裏的問題smtp.PlainAuth拒絕通過未加密的連接發送您的密碼。這是爲了保護你自己。類似smtp.CRAMMD5Auth將是一個更好的選擇。使用CRAM-MD5時,即使通過未加密的連接,您的密碼也不會暴露。

如果仍要使用普通的身份驗證,就需要使自己的smtp.PlainAuth版本。幸運的是,這是一件非常容易的事情。就在20行左右從標準庫複製和刪除:

if !server.TLS { 
    return "", nil, errors.New("unencrypted connection") 
} 

http://golang.org/src/pkg/net/smtp/auth.go?s=1820:1882#L41包含代碼。

如果您不希望複製代碼,你可以通過包裝由函數在自己的類型返回smtp.Auth重用標準庫的實現。通過這種方式,您可以攔截*smtp.ServerInfo並欺騙實際的Auth機制(來自標準庫)存在加密連接。請務必大力評論,以清楚說明你爲什麼在做你正在做的事情。像這樣(未經):

type unencryptedAuth struct { 
    smtp.Auth 
} 

func (a unencryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { 
    s := *server 
    s.TLS = true 
    return a.Auth.Start(&s) 
} 

auth := unencryptedAuth { 
    smtp.PlainAuth(
     "", 
     "[email protected]", 
     "password", 
     "mail.example.com", 
    ), 
}