Go 서버에서 Outlook 메일 전송하기

이정현·2023년 3월 12일
0

Go 서버에서 outlook 메일 발송할 일이 있어서 net/smtp 패키지를 이용해서 발송한 후기를 남기고자 한다.

net/smtp로 메일 발송

우선, smtp 패키지만 사용해서 메일을 발송하는 코드를 짜보았다.

package main

import (
	"log"
	"net/smtp"
	"strconv"
)

func main() {
	server := "smtp-mail.outlook.com"
	port := 587
	from := "some@domain.com"
	pass := "password"
	dest := "ljwh123161@gmail.com"

	auth := smtp.PlainAuth("", from, pass, server)

	msg := []byte("From: " + from + "\n" +
		"To: " + dest + "\n" +
		"Subject: Send test mail\n" +
		"OK")

	endpoint := server + ":" + strconv.Itoa(port)
	err := smtp.SendMail(endpoint, auth, from, []string{dest}, msg)
	if err != nil {
		log.Fatal(err)
	}
}

코드만 보면 문제가 없지만, 에러가 발생했다.

2023/03/12 23:03:47 504 5.7.4 Unrecognized authentication type [SL2P216CA0095.KORP216.PROD.OUTLOOK.COM 2023-03-12T14:03:42.728Z 08DB22F9A7E61B3F]
exit status 1

이유는 outlook 메일이 Plain authentication을 지원하지 않아 발생한 문제였다.(출처)

메일 발송할 때 LOGIN authentication을 사용하는 struct를 만들었고, 이를 이용해서 메일을 발송했더니 성공했다! 여기서 Start와 Next function은 smt.Auth interface가 Start와 Next function을 구현해야 하기 때문에 구현해주었다.

type loginAuth struct {
	username, password string
}

func NewAuth(username, password string) smtp.Auth {
	return &loginAuth{username, password}
}

func (o *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
	fmt.Println(server.Name)
	return "LOGIN", []byte{}, nil
}

func (o *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
	fmt.Println(string(fromServer))
	fmt.Println(more)
	if more {
		switch string(fromServer) {
		case "Username:":
			return []byte(o.username), nil
		case "Password:":
			return []byte(o.password), nil
		default:
			return nil, errors.New("Unkown fromServer")
		}
	}
	return nil, nil
}

참고 : https://stackoverflow.com/questions/57783841/how-to-send-email-using-outlooks-smtp-servers

profile
안녕하세요!

0개의 댓글