在检查SMTP和邮件服务器的设置是否正确的同时,需要检查用户权限是否具有发送邮件的权限。可以通过在代码中指定用户组权限或单独为该用户添加发送邮件的权限来解决。示例代码如下:
import smtplib
# 创建SMTP对象
smtpObj = smtplib.SMTP('mail.example.com', 587)
# 登录
smtpObj.login('user@example.com', 'password')
# 添加用户
user = 'NewUser'
user_permissions = ['Read', 'Write', 'SendEmail']
# 按权限创建用户,此处省略
# 检查用户权限
if 'SendEmail' not in user_permissions:
raise Exception('User does not have permission to send emails')
# 发送邮件
from_addr = 'user@example.com'
to_addr = 'recipient@example.com'
subject = 'Test email'
body = 'This is a test email from {} to {}'.format(from_addr, to_addr)
msg = 'Subject: {}\n\n{}'.format(subject, body)
smtpObj.sendmail(from_addr, to_addr, msg)
# 关闭SMTP连接
smtpObj.quit()