如何使用Python在Gmail中发送邮件?新手项目实现需求
实现用户输入消息发送给指定联系人的方案
针对你的需求,下面给几种常见的实现方式,都是适合新手上手的:
1. 本地测试模拟版本(无需外部服务)
适合先跑通流程,验证输入和函数逻辑,不用实际发送消息:
msginput = input("What would you like to send?: ") recipientinput = input("To whom would you like to send this message?: ") def sending(msginput, recipientinput): # 模拟发送成功的提示 print(f"已成功向 {recipientinput} 发送消息:{msginput}") # 调用函数执行发送 sending(msginput, recipientinput)
2. 发送邮件(用Python自带的smtplib)
可以实现给指定邮箱发送消息,需要先开启邮箱的SMTP服务(比如QQ邮箱要在设置里开启POP3/SMTP,获取授权码):
import smtplib from email.mime.text import MIMEText from email.header import Header msginput = input("What would you like to send?: ") recipientinput = input("请输入收件人邮箱:") def sending(msg_content, recipient_email): # 配置你的邮箱信息 sender_email = "你的邮箱地址@xxx.com" sender_auth_code = "你的邮箱SMTP授权码" # 不是登录密码,是SMTP专用授权码 smtp_server = "smtp.xxx.com" # 比如QQ邮箱是smtp.qq.com,Gmail是smtp.gmail.com smtp_port = 465 # SSL端口,一般是465 # 构造邮件内容 message = MIMEText(msg_content, 'plain', 'utf-8') message['From'] = Header("消息发送工具", 'utf-8') message['To'] = Header(recipient_email, 'utf-8') message['Subject'] = Header("来自消息工具的消息", 'utf-8') try: # 连接SMTP服务器并发送 server = smtplib.SMTP_SSL(smtp_server, smtp_port) server.login(sender_email, sender_auth_code) server.sendmail(sender_email, recipient_email, message.as_string()) print(f"邮件已成功发送到 {recipient_email}") server.quit() except Exception as e: print(f"发送失败:{str(e)}") # 调用函数 sending(msginput, recipientinput)
3. 发送短信(用Twilio服务)
如果要发送短信,需要先安装Twilio的Python库,注册Twilio账号获取SID、AUTH_TOKEN和可用的发送手机号:
# 先安装库:pip install twilio from twilio.rest import Client msginput = input("What would you like to send?: ") recipientinput = input("请输入收件人手机号(格式:+国家代码,比如+8613xxxxxxxxx):") def sending(msg_content, recipient_phone): # 替换成你的Twilio账号信息 account_sid = "你的Twilio账号SID" auth_token = "你的Twilio授权TOKEN" twilio_phone = "你的Twilio发送手机号(格式:+国家代码)" client = Client(account_sid, auth_token) try: message = client.messages.create( body=msg_content, from_=twilio_phone, to=recipient_phone ) print(f"短信已发送,消息ID:{message.sid}") except Exception as e: print(f"发送失败:{str(e)}") # 调用函数 sending(msginput, recipientinput)
内容的提问来源于stack exchange,提问作者key_alt
相关产品推荐
相关产品推荐

