从Python脚本发送电子邮件,不访问传出端口?

2024-09-29 21:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我被蓝主机打败了。我正在做类似的操作to this,除了使用smtp.gmail.com:587而不是IMAP。在

从终端(本地运行)工作得很好,但是I wanted to automate it as a cron job。它今晚无声地失败了,所以我尝试通过SSH,这是我发现的上面的问题-socket.error: [Errno 101] Network is unreachable。在

我有一个共享托管计划,但是Bluehost say that even with a dedicated IP他们只能打开端口>;=1024。在

我被卡住了,没办法吗?对于Python不发送电子邮件,而是用其他方式发送电子邮件的情况,有什么想法。。?在

Bluehost可以在cron作业完成时发送一封电子邮件-以任何方式从Python传递一个变量,这样它就可以为我发送邮件了?在


Tags: tocom终端电子邮件as方式itautomate
2条回答

您可以使用BlueHost为您提供的smtp服务器:

#!/usr/bin/env python
# email functions
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib  
from email.Utils import COMMASPACE, formatdate

lines = ''
lines =  r'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">'
lines += r'<html xmlns="http://www.w3.org/1999/xhtml">'
lines += r'<h1>Hi!'

yourSmtp = 'mail.yourDomain.com'
fromaddr = 'yourEmailName@yourDomain.com'  
password = 'yourPassword'
toaddrs  = ['whoEver@gmail.com']

msg = MIMEMultipart('alternative')
msg['Subject'] = 'Hi'
msg['From'] = fromaddr
msg['Date'] = formatdate(localtime=True)
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText("text", 'plain')
part2 = MIMEText(lines, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

server = smtplib.SMTP(yourSmtp,26)
server.set_debuglevel(0)
server.ehlo(yourSmtp)
server.starttls()
server.ehlo(yourSmtp)
server.login(fromaddr,password)
for toadd in toaddrs:
   msg['To'] = toadd
   server.sendmail(fromaddr, toadd, msg.as_string())  
server.quit()

Bluehost不允许脚本使用标准计划访问80和443以外的其他端口。因为您的脚本尝试使用端口587,所以它根本无法工作。有关Bluehosts策略的更多详细信息,请查看此处:help page on Bluehost

一个建议是你使用另一个电子邮件服务,允许通过另一个端口,即HTTP发送电子邮件。mailgun是一个提供此服务的提供商。在

相关问题 更多 >

    热门问题