MailerSend v2.0.0发送邮件报错:'MailerSendClient'无'send'属性
问题描述
我尝试基于MailerSend的README文档使用MailerSend发送邮件,已通过以下命令安装库:
pip install mailersend
我的脚本代码如下:
from mailersend import MailerSendClient, EmailBuiler from dotenv import load_env load_dotenv() ms = MailerSendClient() email = (EmailBuilder().from_email('emaildomain@domain.com', 'Cybershield Linknguard').to_many([{'email': 'sivuyisencapayi@gmail.com', 'name': 'Sivuyise'}])).subject('Test Email').text('This is a test email from MailerSend').build() response = ms.send(email) if response.status_code == 202: print("Email sent successfully!") else: print("Failed to send email.")
运行python send_email.py时出现如下错误:
Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\Msebetsi Solutions\cyber-shield-linkguard\cyber-shield-linkguard\send_email.py", line 10, in <module> response = ms.send(email) ^^^^^^^ AttributeError: 'MailerSendClient' object has no attribute 'send'
通过pip show mailersend确认当前安装的mailersend版本为2.0.0,已将from_email()参数改为MailerSend提供的域名,但send()方法相关问题仍存在,请问如何修改脚本使其正常运行?
解决方案
MailerSend 2.0.0版本的API与旧版本存在较大差异,MailerSendClient不再提供send方法,需调整代码适配新API:
- 修正导入类与拼写错误:新版本需导入
MailerSend和Email类,同时注意你代码里的EmailBuiler是拼写错误,正确应为EmailBuilder。 - 正确初始化客户端:
MailerSend需传入API密钥,可从环境变量读取(确保.env文件配置了MAILERSEND_API_KEY)。 - 调整邮件构建逻辑:使用
Email类的set_from、add_recipient等方法构建邮件,或直接用字典定义邮件结构。 - 使用新版发送方法:通过客户端的
emails.send方法发送邮件。
修改后的脚本示例(类构建方式):
from mailersend import MailerSend, Email from dotenv import load_dotenv import os load_dotenv() # 从环境变量读取API密钥并初始化客户端 ms = MailerSend(api_key=os.getenv("MAILERSEND_API_KEY")) # 构建邮件对象 email = ( Email() .set_from("emaildomain@domain.com", "Cybershield Linknguard") .add_recipient("sivuyisencapayi@gmail.com", "Sivuyise") .set_subject("Test Email") .set_text("This is a test email from MailerSend") ) # 发送邮件 response = ms.emails.send(email) if response["status"] == "success": print("Email sent successfully!") else: print(f"Failed to send email: {response.get('message')}")
也可使用字典结构直接定义邮件内容,写法更简洁:
from mailersend import MailerSend from dotenv import load_dotenv import os load_dotenv() ms = MailerSend(api_key=os.getenv("MAILERSEND_API_KEY")) email_data = { "from": {"email": "emaildomain@domain.com", "name": "Cybershield Linknguard"}, "to": [{"email": "sivuyisencapayi@gmail.com", "name": "Sivuyise"}], "subject": "Test Email", "text": "This is a test email from MailerSend" } response = ms.emails.send(email_data) if response["status"] == "success": print("Email sent successfully!") else: print(f"Failed to send email: {response.get('message')}")
注意事项:
- 确保
.env文件中配置了正确的MAILERSEND_API_KEY,该密钥可在MailerSend后台获取。 - 发件邮箱必须是MailerSend后台已验证的域名/邮箱地址。
内容的提问来源于stack exchange,提问作者siv.ncapayi
相关产品推荐
相关产品推荐

