본문 바로가기

개발일기/go

[golang] outlook 메일 전송

outlook 메일 전송은

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

이 코드가 안먹는다.

뭘 바꿔도 자꾸 에러가 나서 봤더니만.. 역시 아웃룩은..(더보기)

 

const (
	mailServer      = "smtp-mail.outlook.com"
	mailPort        = "587"
	mailUser        = "sender@outlook.kr"
	mailPassword    = "password"
	mailDestination = "sender@outlook.kr"
)

type loginAuth struct {
	username, password string
}

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

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

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

func sendMail() {
	// 추후 변수 db에서 불러올 수 있도록 수정
	endpoint := mailServer + ":" + mailPort

	auth := LoginAuth(mailUser, mailPassword)

	from := mailUser
	to := []string{mailDestination}

	headerSubject := "Subject: 테스트\r\n"
	headerBlank := "\r\n"
	body := "메일 테스트입니다\r\n"
	msg := []byte(headerSubject + headerBlank + body)

	err := smtp.SendMail(endpoint, auth, from, to, []byte(msg))
	if err != nil {
		fmt.Printf("err : %v", err)
	}
}

func main(){
	sendMail()
}

 

이렇게 전송하면 잘 돌아간다

 

코드 참고 링크

https://gist.github.com/andelf/5118732

 

golang net/smtp SMTP AUTH LOGIN Auth Handler

golang net/smtp SMTP AUTH LOGIN Auth Handler. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

 

아 참고로 outlook.com에서 pop 엑세스 사용가능 설정 해줘야 한다.

outlook 앱에서 찾으면 저게 없는 경우가 있다;

저 링크를 클릭해서 해주도록 하자

해당 설명 링크

https://support.microsoft.com/ko-kr/office/outlook-com%EC%9D%98-pop-imap-%EB%B0%8F-smtp-%EC%84%A4%EC%A0%95-d088b986-291d-42b8-9564-9c414e2aa040