Golang Email

Backup Code

I dont have chinese inputmethod now ( what the fuck about Linux KDE envirnment !) , so just leave some message for this backup code about golang email . I remember that I had written this function a long time ago , but I can not find it out just now . Some code was searched on Internet .

This is a example for QQ email . But you can use other email ,eg 163,yahoo... But you must config the server smtp address .

Here it is :

// EmailMain
package main

import (
	"fmt"
	"net/smtp"
	"strings"
)

const(
	HOST = "smtp.qq.com"
	SERVER_ADDR = "smtp.qq.com:25"
	USER = "624432528@qq.com"
	PASSWORD = "xxxx"
)

type Email struct {
	to string "to"
	subject string "subject"
	msg string "msg"
}

func NewEmail(to,subject,msg string) *Email{
	return &Email{to:to,subject:subject,msg:msg}
}

func SendEmail(email *Email) error{
	auth := smtp.PlainAuth("",USER,PASSWORD,HOST)
	sendTo := strings.Split(email.to,";")
	done := make(chan error,1024)
	
	go func(){
		defer close(done)
		for _,v := range sendTo {
			//warning ; the last \r\n need twice , not only one .
			str := strings.Replace("From:"+USER+"~To :"+v+"~Subject:"+email.subject+"~Content-Type: text/plain;charset=UTF-8~","~","\r\n",-1)+"\r\n"+email.msg
			fmt.Println("Content:",str)
			err := smtp.SendMail(SERVER_ADDR,auth,USER,[]string{v},[]byte(str))
			if err != nil{
				fmt.Println("Send Error:",err)
			}
			done <- err
		}
	}()
		
	for i:=0;i<len(sendTo);i++{
		<- done
	}

	return nil
}

func main() {
	email := NewEmail("798207330@qq.com","How Are you","Hello World , I am wang")
	err := SendEmail(email)
	fmt.Println("result:",err)
}

posted @ 2015-06-30 23:07  薛定谔的猫_  阅读(601)  评论(0编辑  收藏  举报