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

使用Python smtplib发邮件遇[WinError 10061]连接被拒求助

问题描述

公司内网VPN环境下,Spyder与R使用相同代理设置,用Python的smtplib包发送内部邮件时,执行smtpserver.connect()报错[WinError 10061]目标机器主动拒绝连接;但用R的Blastula包编写的相同逻辑脚本却能正常发送邮件,求排查方案。

排查方案
  • 修正SMTP_SSL参数错误:
    你Python代码里把SMTP服务器地址填到了local_hostname参数,这是完全错误的——local_hostname是本地主机标识,不是远程SMTP服务器地址。正确写法是把服务器地址传给host参数,且要去掉smtp://前缀。另外,端口25一般是非SSL端口,R的use_ssl=TRUE大概率是用了STARTTLS加密而非直接SSL连接,可尝试两种写法:
    直接SSL连接(若服务器465端口开放):
    smtpserver = smtplib.SMTP_SSL(host="foo-corporate.com", port=465)
    
    或先连接25端口再启动TLS:
    smtpserver = smtplib.SMTP(host="foo-corporate.com", port=25)
    smtpserver.starttls()
    
  • 手动配置代理:
    R的Blastula会自动读取系统/VPN的代理设置,但Python的smtplib不会。如果VPN需要代理,手动设置环境变量:
    import os
    os.environ['http_proxy'] = 'http://你的代理地址:端口'
    os.environ['https_proxy'] = 'http://你的代理地址:端口'
    
    若使用SOCKS代理,需用socks库包装smtplib:
    import socks
    import smtplib
    
    socks.set_default_proxy(socks.SOCKS5, "代理主机", 代理端口)
    socks.wrapmodule(smtplib)
    
    # 初始化SMTP连接
    smtpserver = smtplib.SMTP("foo-corporate.com", 25)
    smtpserver.starttls()
    
  • 补全认证步骤:
    你的Python代码缺少登录认证步骤,而R脚本配置了完整凭据。SMTP连接成功后必须调用smtpserver.login(corp_user, corp_pwd),否则服务器可能直接拒绝连接。
  • 验证服务器连通性:
    先用PowerShell测试SMTP服务器的连通性:
    Test-NetConnection foo-corporate.com -Port 25
    
    若无法连通,先排查VPN或网络设置;能连通再调试Python代码。
  • 确认服务器端口规则:
    咨询IT部门,确认公司内部SMTP服务器的25端口是否支持直接SSL连接。很多企业内部SMTP是在25端口使用STARTTLS加密,直接用SMTP_SSL连接25端口会被拒绝。
用户提供的原代码

Python代码

import smtplib

to = 'foo@foo-corporate.com'
corp_user = 'foo@foo-corporate.com'
corp_pwd = 'password'
smtpserver = smtplib.SMTP_SSL(local_hostname="smtp://foo-corporate.com", port = 25)
smtpserver.connect()

R代码

library(blastula)

create_smtp_creds_key(
  id = "email_creds",
  user = "foo@foo-corporate.com",
  host = "smtp://foo-corporate.com",
  port = 25,
  use_ssl = TRUE
)

email <-
  compose_email(
    body = md(" Hello, 
        This is a test email
        "))
  
# Sending email by SMTP using a credentials file
email %>%
  smtp_send(
    to = "foo@foo-corporate.com",
    from = "foo@foo-corporate.com",
    subject = "Testing the `smtp_send()` function",
    credentials = creds_key("email_creds")
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:20:37