Content | Example |
Date | Mon, 29 Jun 2009 18:39:03 +0800 |
From | abc@123.com |
To | abc1@123.com |
BCC | abc3@123.com |
Subject | test |
Message-ID | 123@123.com |
Mime-Version | 1.0 |
Field | Description |
Bcc | Blind carbon copy address |
Cc | Copy address |
Content-Transfer-Encoding | Content transfer encoding method |
Content-Type | Content type |
Date | Date and time |
Delivered-To | Recipient address |
From | Sender address |
Message-ID | Message ID |
MIME-Version | MIME version |
Received | Transfer path |
Reply-To | Reply-to address |
Return-Path | Reply-to address |
Subject | Subject |
To | Recipient address |
Field | Description |
Content-ID | Content ID |
Content-Transfer-Encoding | Content transfer encoding method |
Content-Location | Content location (path) |
Content-Base | Content base location |
Content-Disposition | Content disposition method |
Content-Type | Content type |
Content-Type field in the email header.
multipart/mixed part. If there are embedded resources, you must define at least the multipart/related part; if plain text and hypertext coexist, you must define at least the multipart/alternative part.package mainimport ("bytes""crypto/tls""encoding/base64""fmt""io/ioutil""log""mime""net""net/smtp""time")// Test465Attachment for port 465func Test465Attachment() error {boundary := "GoBoundary"host := "sg-smtp.qcloudmail.com"port := 465email := "abc@cd.com"password := "***"toEmail := "test@test123.com"header := make(map[string]string)header["From"] = "test " + "<" + email + ">"header["To"] = toEmailheader["Subject"] = "Test465Attachment"header["Content-Type"] = "multipart/mixed;boundary=" + boundary// This field is not used for the time being. Pass in `1.0` by defaultheader["Mime-Version"] = "1.0"// This field is not used for the time beingheader["Date"] = time.Now().String()bodyHtml := "<!DOCTYPE html>\\n<html>\\n<head>\\n<meta charset=\\"utf-8\\">\\n<title>hello world</title>\\n</head>\\n<body>\\n " +"<h1>My first heading</h1>\\n <p>My first paragraph.</p>\\n</body>\\n</html>"message := ""for k, v := range header {message += fmt.Sprintf("%s: %s\\r\\n", k, v)}buffer := bytes.NewBuffer(nil)buffer.WriteString(message)contentType := "Content-Type: text/html" + "; charset=UTF-8"body := "\\r\\n--" + boundary + "\\r\\n"body += contentType + "\\r\\n"body += "Content-Transfer-Encoding: base64\\r\\n"body += "\\r\\n" + base64.StdEncoding.EncodeToString([]byte(bodyHtml)) + "\\r\\n"attachment := "\\r\\n--" + boundary + "\\r\\n"attachment += "Content-Transfer-Encoding:base64\\r\\n"attachment += "Content-Disposition:attachment\\r\\n"attachment += "Content-Type:" + "application/octet-stream" + ";name=\\"" + mime.BEncoding.Encode("UTF-8","./go.mod") + "\\"\\r\\n"buffer.WriteString(attachment)writeFile(buffer, "./go.mod")// Multiple attachments can be spliced at the end. There can be 10 attachments at most, each of which cannot exceed 5 MB in size. The TOTAL size of all attachments cannot exceed 8–9 MB; otherwise, EOF will be returnedattachment1 := "\\r\\n--" + boundary + "\\r\\n"attachment1 += "Content-Transfer-Encoding:base64\\r\\n"attachment1 += "Content-Disposition:attachment\\r\\n"attachment1 += "Content-Type:" + "application/octet-stream" + ";name=\\"" + mime.BEncoding.Encode("UTF-8","./bbbb.txt") + "\\"\\r\\n"buffer.WriteString(attachment1)writeFile(buffer, "./bbbb.txt")defer func() {if err := recover(); err != nil {log.Fatalln(err)}}()buffer.WriteString("\\r\\n--" + boundary + "--")message += "\\r\\n" + bodyauth := smtp.PlainAuth("",email,password,host,)err := SendMailWithTLS(fmt.Sprintf("%s:%d", host, port),auth,email,[]string{toEmail},buffer.Bytes(),)if err != nil {fmt.Println("Send email error:", err)} else {fmt.Println("Send mail success!")}return err}// Dial return a smtp clientfunc Dial(addr string) (*smtp.Client, error) {conn, err := tls.Dial("tcp", addr, nil)if err != nil {log.Println("tls.Dial Error:", err)return nil, err}host, _, _ := net.SplitHostPort(addr)return smtp.NewClient(conn, host)}// SendMailWithTLS send email with tlsfunc SendMailWithTLS(addr string, auth smtp.Auth, from string,to []string, msg []byte) (err error) {//create smtp clientc, err := Dial(addr)if err != nil {log.Println("Create smtp client error:", err)return err}defer c.Close()if auth != nil {if ok, _ := c.Extension("AUTH"); ok {if err = c.Auth(auth); err != nil {log.Println("Error during AUTH", err)return err}}}if err = c.Mail(from); err != nil {return err}for _, addr := range to {if err = c.Rcpt(addr); err != nil {return err}}w, err := c.Data()if err != nil {return err}_, err = w.Write(msg)if err != nil {return err}err = w.Close()if err != nil {return err}return c.Quit()}// writeFile read file to bufferfunc writeFile(buffer *bytes.Buffer, fileName string) {file, err := ioutil.ReadFile(fileName)if err != nil {panic(err.Error())}payload := make([]byte, base64.StdEncoding.EncodedLen(len(file)))base64.StdEncoding.Encode(payload, file)buffer.WriteString("\\r\\n")for index, line := 0, len(payload); index < line; index++ {buffer.WriteByte(payload[index])if (index+1)%76 == 0 {buffer.WriteString("\\r\\n")}}}func main() {Test465Attachment()}
#!/usr/bin/env python3# -*- coding: utf-8 -*-import smtplibimport osfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersfrom email.utils import formatdatefrom email.header import Headerimport ssldef send_email_with_attachments():host = "smtp.qcloudmail.com"port = 465email = "abc@cd.com"password = "****"to_email = "test@test123.com"msg = MIMEMultipart('mixed')msg['From'] = f"test <{email}>"msg['To'] = to_emailmsg['Subject'] = "Test465Attachment"msg['Date'] = formatdate(localtime=True)msg['Mime-Version'] = "1.0"html_body = """<!DOCTYPE html><html><head><meta charset="utf-8"><title>hello world</title></head><body><h1>my first head</h1><p>my first paragraph</p></body></html>"""# add HTMLhtml_part = MIMEText(html_body, 'html', 'utf-8')msg.attach(html_part)# add attachmentattachments = ["./name.txt"]for attachment_path in attachments:if os.path.exists(attachment_path):try:with open(attachment_path, 'rb') as file:attachment_data = file.read()attachment_part = MIMEBase('application', 'octet-stream')attachment_part.set_payload(attachment_data)encoders.encode_base64(attachment_part)filename = os.path.basename(attachment_path)encoded_filename = Header(filename, 'utf-8').encode()attachment_part.add_header('Content-Disposition',f'attachment; filename="{encoded_filename}"')msg.attach(attachment_part)print(f"add attachment successfully: {filename}")except Exception as e:print(f"add attachment {attachment_path} error: {e}")else:print(f"attachment missing: {attachment_path}")try:context = ssl.create_default_context()with smtplib.SMTP_SSL(host, port, context=context) as server:server.login(email, password)server.send_message(msg)print("send email success")return Trueexcept Exception as e:print(f"send email error: {e}")return Falseif __name__ == "__main__":print("start sending email with attachment...")send_email_with_attachments()
Feedback