You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发邮件客户端发送邮件遇AttributeError及字符串拼接错误求助

解决邮件客户端发送邮件时的AttributeError及字符串拼接错误

问题根源分析

你遇到的错误提示can only concatenate str (not "AttributeError") to str来自SMTP连接异常处理中的字符串拼接错误,同时还有一个核心问题:self.attachments未初始化,首次调用时会触发AttributeError,这也是发送失败的主要原因之一。

具体修复步骤

1. 修复字符串拼接错误

在send_email函数的SMTP连接异常块中,直接将字符串和Exception对象e拼接违反Python语法,需将异常转为字符串或使用f-string格式化:

原错误代码:

QMessageBox.critical(self, 'Error', 'Failed to connect to the SMTP server'+ e)

修复后(推荐f-string写法):

QMessageBox.critical(self, 'Error', f'Failed to connect to the SMTP server: {e}')

2. 初始化attachments列表

你的compose_email和add_attachment直接使用self.attachments,但未在类初始化时定义该属性,首次调用会触发AttributeError。需在类的__init__方法中添加:

def __init__(self, parent=None):
    # 保留原有的初始化代码
    self.attachments = []  # 初始化附件列表

3. 补充GMX SMTP的加密步骤

GMX的SMTP服务器要求STARTTLS加密,原代码缺少该步骤,会导致连接失败。在smtp_server.login前添加:

smtp_server.starttls()

4. 优化异常捕获范围(可选)

原compose_email的try块范围过小,建议将整个发送逻辑纳入捕获范围,同时发送后清空附件列表:

if result == QDialog.Accepted:
    try:
        recipient = self.recipient_field.text()
        subject = self.subject_field.text()
        message = self.message_field.toPlainText()
        attachments = self.attachments.copy()  # 复制列表避免后续操作干扰
        self.send_email(recipient, subject, message, attachments)
        self.attachments.clear()  # 发送完成后清空附件列表
    except Exception as e:
        print("发送邮件时出错:", e)

完整修复后的send_email函数

def send_email(self, recipient, subject, message, attachments):
    # 连接SMTP服务器
    try:
        smtp_server = smtplib.SMTP('smtp.gmx.com',587)
        smtp_server.starttls()  # 新增STARTTLS加密
        smtp_server.login(self.mailbox.username, self.mailbox.password)
    except Exception as e:
        QMessageBox.critical(self, 'Error', f'连接SMTP服务器失败: {e}')
        return

    # 创建邮件对象
    msg = email.message.EmailMessage()
    msg['From'] = self.mailbox.username  # 用username替代user,避免属性错误
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.set_content(message)
    
    # 添加附件
    for file_name in attachments:
        try:
            with open(file_name, 'rb') as f:
                file_data = f.read()
                file_name = os.path.basename(file_name)
                msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
        except Exception as e:
            QMessageBox.warning(self, 'Warning', f'添加附件 {file_name} 失败: {e}')
            continue

    # 发送邮件
    try:
        smtp_server.send_message(msg)
    except Exception as e:
        QMessageBox.critical(self, 'Error', f'发送邮件失败: {e}')
        return

    smtp_server.quit()
    QMessageBox.information(self, 'Success', '邮件发送成功')

内容的提问来源于stack exchange,提问作者Ahmad Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:25:25