golang
golang smtp email send
kimbs0301
2025. 1. 5. 10:37
Gmail SMTP 사용을 위한 세팅
구글 이메일 설정에서 모든 설정 보기 메뉴 이동
전달 및 POP/IMAP 탭
SMTP를 이용하려면 IMAP사용 체크
구글 계정 설정 메뉴이동
보안 탭
앱 비밀번호 생성 및 메모
main.go
// Package main
package main // import "myhost.com/smtp/main"
import (
"errors"
"fmt"
"net/smtp"
)
// main
func main() {
uername := "xxx@gmail.com"
password := "xxxx xxxx xxxx xxxx"
auth := gmailLoginAuth(uername, password)
from := "xxx@gmail.com"
to := "xxx@gmail.com"
subject := "이메일 제목"
body := "이메일 내용"
msg := "From: " + from + "\r\n" + "To: " + to + "\r\n" + "Subject: " + subject + "\r\n\r\n" + body + "\r\n"
err = smtp.SendMail("smtp.gmail.com:587", auth, from, []string{to}, []byte(msg))
if err != nil {
fmt.Printf("smtp error: %s", err.Error())
}
}
// loginAuth
type loginAuth struct {
username, password string
}
// gmailLoginAuth
func gmailLoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
// Start
func (l *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
// Next
func (l *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(l.username), nil
case "Password:":
return []byte(l.password), nil
default:
return nil, errors.New("Unkown fromServer")
}
}
return nil, nil
}