SMTP를 사용하여 Go로 이메일을 보내는 방법

이 기사에서는 SMTP를 사용하여 Golang으로 이메일을 보내는 방법을 보여 드리겠습니다.

이메일을 보내기 위해 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 공급자를 사용하는 경우 hostport 값을 바꿉니다.
    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.")
    }
    


    이 기사가 통찰력이 있기를 바랍니다.

    🌎연결해봅시다.
  • 내 블로그 kirandev.com
  • 팔로우
  • Github에서 나를 찾아라
  • 좋은 웹페이지 즐겨찾기