ZBLOG

go 发送短信

在 Go 语言中发送短信通常需要通过第三方短信服务提供商的 API 实现。以下是几种常见的实现方式及代码示例:


1. 通过 HTTP API 调用短信服务商

主流短信平台(如阿里云、腾讯云、Twilio)均提供 RESTful API。

示例:使用 Twilio 发送短信

package main

import (
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

func sendSMSViaTwilio(accountSID, authToken, from, to, message string) error {
	// Twilio API 地址
	endpoint := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", accountSID)

	// 构造表单数据
	data := url.Values{}
	data.Set("To", to)
	data.Set("From", from)
	data.Set("Body", message)

	// 创建 HTTP 请求
	req, err := http.NewRequest("POST", endpoint, strings.NewReader(data.Encode()))
	if err != nil {
		return err
	}

	// 设置认证头 (Basic Auth)
	req.SetBasicAuth(accountSID, authToken)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	// 发送请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		return fmt.Errorf("HTTP error: %s", resp.Status)
	}

	fmt.Println("短信发送成功!")
	return nil
}

func main() {
	err := sendSMSViaTwilio(
		"your_account_sid",
		"your_auth_token",
		"+1234567890", // Twilio提供的号码
        "+8613800138000", // 接收方号码(带国际区号)
        "您的验证码是: 1234",
    )
    if err != nil {
        panic(err)
    }
}

2. 使用国内短信服务商(如阿里云)

示例:阿里云短信 SDK

package main

import (
    "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

func sendSMSViaAliyun(accessKeyId, accessSecret, phoneNumbers, signName, templateCode string) error {
    client, err := dysmsapi.NewClientWithAccessKey(
        "cn-hangzhou",          // Region ID
        accessKeyId,
        accessSecret,
    )
    if err != nil {
        return err
    }

    request := dysmsapi.CreateSendSmsRequest()
    request.Scheme = "https"
    
    request.PhoneNumbers = phoneNumbers   // 接收号码(多个用逗号分隔)
    request.SignName = signName           // 短信签名(需审核)
    request.TemplateCode = templateCode   // 模板ID(需审核)
    request.TemplateParam = `{"code":"1234"}` // JSON参数

    response, err := client.SendSms(request)
    if err != nil {
        return err
    }

    if response.Code != "OK" {
        return fmt.Errorf("API错误: %s", response.Message)
    }
    
    return nil
}

3. SMTP+邮件网关转发短信

部分运营商支持通过邮件发送短信(如中国移动的139邮箱):

import (
    "net/smtp"
)

func sendSMSToMobileEmail(toPhoneNumber string) error {
     from := "your_email@example.com"
     password := "email_password"

     smtpHost := "smtp.example.com"
     smtpPort := "587"

     msg := []byte(fmt.Sprintf(
         `To: %s@139.com   //中国移动号码对应邮箱后缀 
         Subject: SMS Forward\n\nThis is your SMS content`,
         toPhoneNumber,
     ))

     auth := smtp.PlainAuth("", from, password, smtpHost)
     return smtp.SendMail(smtpHost+":"+smtpPort, auth, from, []string{toPhoneNumber + "@139.com"}, msg)
}

关键注意事项

  1. 安全敏感信息
    • AccessKey、账号密码等应通过环境变量或配置中心加载,避免硬编码。
  2. 错误处理
    • API调用需检查HTTP状态码和响应体中的业务错误码。
  3. 性能优化
    • 高频发送建议使用连接池或异步队列(如Kafka + Worker)。
  4. 合规性
    • 国内短信需提前申请签名和模板,内容需符合运营商规范。

如果需要具体平台的完整SDK文档或调试帮助,可以进一步说明需求!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23841

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?