tencent cloud

Sample Call for Go

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-05-12 16:00:22
The following sample code uses SMTP to send an email in Go language (v1.16):
// Email Push Service (SES) using the SMTP protocol.
//
// This code demonstrates how to send an email request to Tencent Cloud SES
// via the SMTP protocol (port 465 with SSL/TLS encryption). The overall flow
// consists of the following steps:
// 1. Prepare sending parameters (sender, recipients, Cc, Bcc, subject, body, etc.);
// 2. Assemble the email Header and Body in RFC 822 format (the Body is Base64-encoded);
// 3. Establish an encrypted connection to the SMTP server using tls.Dial;
// 4. Complete authentication via PlainAuth;
// 5. Execute SMTP commands such as MAIL FROM, RCPT TO and DATA in order to deliver the message.
//
// Before using this code, please complete the following preparations in the
// Tencent Cloud Email Push console:
// - Create and verify a Sender Domain;
// - Create a Sender Address and enable SMTP sending;
// - Generate a dedicated SMTP password under "SMTP Password" in the console
// (note: this is NOT your Tencent Cloud account password);
// - Make sure the sender address has available sending quota.
//
// Dependencies: only the standard library net/smtp and crypto/tls; no third-party packages required.
package main

import (
"crypto/tls"
"encoding/base64"
"fmt"
"log"
"net"
"net/smtp"
)

// Test465 demonstrates sending an HTML-formatted email via port 465 (SSL/TLS).
//
// Workflow:
// 1. Configure the SMTP server address, port, sender account and SMTP password;
// 2. Build the email headers (From / To / Cc / Bcc / Subject / Content-Type, etc.);
// 3. Base64-encode the body and append it after the headers (a blank line is required between header and body);
// 4. Use smtp.PlainAuth to create a PLAIN authentication object;
// 5. Call SendMailWithTLS to deliver the message via a TLS connection.
//
// Return value: returns nil on success, or the specific error on failure.
func Test465() error {
// SMTP server address. For Tencent Cloud Email Push it is fixed to smtp.qcloudmail.com.
host := "smtp.qcloudmail.com"
// SMTP port: 465 means an SSL/TLS encrypted connection;
// If you want to use STARTTLS, switch to port 25, and the tls.Dial in the code
// must be changed to net.Dial + StartTLS accordingly.
port := 465

// email: the Sender Address that has been created and verified in the console;
// it must match the account that owns the SMTP password.
email := "abc@cd.com"
// password: the dedicated SMTP password generated for this sender address
// in the "SMTP Settings" page of the console.
// It is NOT your Tencent Cloud login password and NOT the API key.
password := "****"

// Recipient address (required, at least one)
toEmail := "test@test123.com"
// Cc address (optional)
ccEmail := "cc@test123.com"
// Bcc address (optional)
bccEmail := "bcc@test123.com"

// Build the email header. The SMTP protocol requires header fields to be
// written as "Key: Value\\r\\n", and a blank line ("\\r\\n") is required after
// all headers, followed by the body.
header := make(map[string]string)
// "From" is recommended to be in the form "Display Name <sender address>";
// the display name will be shown as the sender's nickname in the inbox.
header["From"] = "test " + "<" + email + ">"
header["To"] = toEmail
header["Cc"] = ccEmail
header["Bcc"] = bccEmail
// Email subject. If it contains non-ASCII characters, RFC 2047 encoding
// (=?UTF-8?B?...?=) is recommended. This example uses pure ASCII so no encoding is applied.
header["Subject"] = "test subject"

// Content-Type specifies that the body is HTML and declares the charset as UTF-8.
header["Content-Type"] = "text/html; charset=UTF-8"
// Content-Transfer-Encoding specifies the transfer encoding of the body.
// Using base64 prevents non-ASCII or special characters from being truncated
// or corrupted during SMTP transmission.
header["Content-Transfer-Encoding"] = "base64"

// Sample HTML body
body := "<!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>"

// To send a plain-text email, comment out the HTML configuration above
// and enable the following two lines:
//header["Content-Type"] = "text/plain; charset=UTF-8"
//body := "test body"

// Assemble the final SMTP message: first concatenate every header into
// "Key: Value\\r\\n", then add a blank line as separator, and finally append
// the Base64-encoded body.
message := ""
for k, v := range header {
message += fmt.Sprintf("%s: %s\\r\\n", k, v)
}
message += "\\r\\n" + base64.StdEncoding.EncodeToString([]byte(body))

// Create a PLAIN authentication object.
// The 1st parameter "identity" is usually empty; the 2nd is the username
// (the sender address); the 3rd is the SMTP password; the 4th is the host
// (used for server-side validation).
auth := smtp.PlainAuth(
"",
email,
password,
host,
)

// Call the TLS sending function with the server address, auth object,
// sender, recipient list and the raw message.
// Note: the "to" list is used for the SMTP RCPT TO command and determines
// which mailboxes actually receive the email. If you want Cc/Bcc recipients
// to actually receive the message, you must also add ccEmail / bccEmail to this list.
err := SendMailWithTLS(
fmt.Sprintf("%s:%d", host, port),
auth,
email,
[]string{toEmail},
[]byte(message),
)
if err != nil {
fmt.Println("Send email error:", err)
} else {
fmt.Println("Send mail success!")
}
return err
}

// Dial establishes a TLS-encrypted connection to the SMTP server and returns
// a usable *smtp.Client.
//
// Parameter:
// - addr: server address in the form "host:port", e.g. "smtp.qcloudmail.com:465".
//
// Notes:
// - The standard library's smtp.Dial uses a plain connection by default.
// For port 465 a TLS channel must be established first and then wrapped
// into an SMTP client, so this function uses tls.Dial instead of net.Dial.
// - The second argument is *tls.Config; passing nil means using the default
// configuration (which validates the server certificate).
// To skip certificate validation (NOT recommended for production), pass
// &tls.Config{InsecureSkipVerify: true}.
func 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
}

// smtp.NewClient needs the host (without the port) for the EHLO/HELO handshake.
host, _, _ := net.SplitHostPort(addr)
return smtp.NewClient(conn, host)
}

// SendMailWithTLS performs a complete email delivery over a TLS-encrypted SMTP connection.
//
// Parameters:
// - addr: SMTP server address in the form "host:port".
// - auth: SMTP authentication object, can be created by smtp.PlainAuth;
// pass nil if no authentication is required.
// - from: the sender address used in the MAIL FROM command; should match the authenticated account.
// - to: recipient list used in the RCPT TO command, including all real recipients
// of To, Cc and Bcc.
// - msg: the complete email message (Header + blank line + Body), in RFC 822 format.
//
// Steps:
// 1. Establish a TLS + SMTP connection via Dial;
// 2. If the server supports the AUTH extension, perform authentication;
// 3. Execute MAIL FROM, RCPT TO and DATA commands in order;
// 4. Write the email body and close the data stream;
// 5. Call the QUIT command to gracefully close the session.
//
// Any failed step will immediately return the corresponding error.
func SendMailWithTLS(addr string, auth smtp.Auth, from string,
to []string, msg []byte) (err error) {
// 1. Establish the TLS connection and obtain the SMTP client.
c, err := Dial(addr)
if err != nil {
log.Println("Create smtp client error:", err)
return err
}
// Make sure the connection is finally closed to avoid connection leaks.
defer c.Close()

// 2. If auth is provided and the server advertises the AUTH extension via EHLO,
// perform authentication.
if auth != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(auth); err != nil {
log.Println("Error during AUTH", err)
return err
}
}
}

// 3. Send the MAIL FROM command to tell the server who the sender is.
if err = c.Mail(from); err != nil {
return err
}
// 4. Send a RCPT TO command for each recipient.
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}

// 5. Send the DATA command and obtain a writer to write the email content (Header + Body).
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(msg)
if err != nil {
return err
}
// Close the writer to mark the end of the body input
// (in the SMTP protocol the end is indicated by "\\r\\n.\\r\\n").
err = w.Close()
if err != nil {
return err
}

// 6. Send the QUIT command to gracefully end the session with the server.
return c.Quit()
}

// main is the entry point that directly calls Test465 to trigger a send.
// In real business integration, it is recommended to extract sending parameters
// (account, password, recipients, etc.) into configuration or function arguments,
// and to perform finer-grained error handling and retries on Test465.
func main() {
Test465()
}



Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan