SMTP를 사용하여 Go로 이메일을 보내는 방법
11374 단어 smtpbeginnersgoprogramming
이메일을 보내기 위해 SMTP을 사용할 것입니다. 모든 SMTP 서비스를 사용할 수 있지만 여기서는 Mailtrap을 사용하겠습니다. Mailtrap은 테스트 도구이며 실제 주소로 이메일을 전달하도록 설계되지 않았습니다.
다음은 고려할 수 있는 몇 가지 SMTP 공급자입니다.
설정 지침을 이해하려면 해당 문서를 참조하십시오.
SMTP를 사용하여 이메일을 보내려면 SMTP 공급자로부터 아래 정보를 수집해야 합니다.
send-email
라는 새 폴더를 만듭니다.mkdir send-email
cd send-email
touch main.go
main.go
를 열고 필요한 패키지를 가져옵니다.package main
import (
"fmt"
"net/smtp"
)
SMTP 구성을 저장할 변수를 선언해 보겠습니다.
func main() {
// SMTP configuration
username := "<smtp username>"
password := "<smtp password>"
host := "smtp.mailtrap.io"
port := "25"
}
다른 SMTP 공급자를 사용하는 경우
host
및 port
값을 바꿉니다.subject
, body
, from
, to
를 저장할 변수를 추가합니다.// Subject and body
subject := "Simple HTML Email"
body := "Here is a simple plain text."
// Sender and receiver
from := "[email protected]"
to := []string{
"[email protected]",
}
이제 보낼 메시지를 작성해 보겠습니다.
from
, to
, subject
, body
를 추가하여 message
를 생성합니다. 메시지 줄은 CRLF 문자로 구분됩니다.// Build the message
message := fmt.Sprintf("From: %s\r\n", from)
message += fmt.Sprintf("To: %s\r\n", to)
message += fmt.Sprintf("Subject: %s\r\n", subject)
message += fmt.Sprintf("\r\n%s\r\n", body)
이제
PlainAuth
메서드를 호출하여 SMTP 서버로 인증을 시작합니다. PlainAuth는 PLAIN 인증 메커니즘을 구현하는 Auth를 반환합니다.// Authentication.
auth := smtp.PlainAuth("", username, password, host)
이제
SendMail
방법을 사용하여 이메일을 보냅니다. 이 메서드는 이메일 전송에 실패하면 오류를 반환합니다. 오류를 제대로 포착했는지 확인하십시오.// Send email
err := smtp.SendMail(host+":"+port, auth, from, to, []byte(message))
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email sent successfully.")
다음은 전체 작업 코드입니다.
package main
import (
"fmt"
"net/smtp"
)
func main() {
// SMTP configuration
username := "<SMTP username>"
password := "<SMTP password>"
host := "<SMTP host>"
port := "25"
// Subject and body
subject := "Simple HTML Email"
body := "Here is a simple plain text."
// Sender and receiver
from := "[email protected]"
to := []string{
"[email protected]",
}
// Build the message
message := fmt.Sprintf("From: %s\r\n", from)
message += fmt.Sprintf("To: %s\r\n", to)
message += fmt.Sprintf("Subject: %s\r\n", subject)
message += fmt.Sprintf("\r\n%s\r\n", body)
// Authentication.
auth := smtp.PlainAuth("", username, password, host)
// Send email
err := smtp.SendMail(host+":"+port, auth, from, to, []byte(message))
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email sent successfully.")
}
이 기사가 통찰력이 있기를 바랍니다.
🌎연결해봅시다.
Reference
이 문제에 관하여(SMTP를 사용하여 Go로 이메일을 보내는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/devkiran/how-to-send-an-email-with-golang-using-smtp-1ino텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)