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

如何修复Python中的TypeError: 'SMTP_SSL' object is not callable错误

解决Python中TypeError: 'SMTP_SSL' object is not callable错误

问题场景

执行Python邮件发送代码时触发TypeError: 'SMTP_SSL' object is not callable错误,相关代码如下:

邮件发送代码(fun.py)

import smtplib, ssl

def show_im_having_fun():
 return

smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()).login('hello@gmail.com', 'pass')

smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context())('email@gmail.com',"receemail",  message = 'Subject: {}\n\n{}'.format('this is subject', """\\ Hello World """))

print("sent")

导入调用代码

from fun import show_im_having_fun

show_im_having_fun()
print(show_im_having_fun())

错误原因与解决方法

  • 错误根源:第二处smtplib.SMTP_SSL(...)()的写法完全错误。SMTP_SSL()返回的是一个实例对象,不能直接用()调用,发送邮件必须调用对象的sendmail方法。
  • 修正方案:
    1. 复用SMTP_SSL连接实例,避免重复建立连接
    2. 调用sendmail方法完成邮件发送,同时用with语句自动管理连接生命周期

修正后的邮件发送代码:

import smtplib, ssl

def show_im_having_fun():
    return

context = ssl.create_default_context()
# 用with语句自动管理连接
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login('hello@gmail.com', 'pass')
    # 构造标准格式的邮件内容
    subject = 'this is subject'
    body = "\\ Hello World "
    message = f'Subject: {subject}\n\n{body}'
    # 调用sendmail发送邮件
    server.sendmail('email@gmail.com', "receemail", message)

print("sent")

额外说明

  • show_im_having_fun函数目前无实际业务逻辑,若无需保留可直接移除
  • Gmail账号需开启低安全性应用权限或使用应用专用密码才能正常通过SMTP发送邮件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:45:32