我最近编写了一个脚本,如果我想要监控的网站使用smtplib进行了更改,则会向我发送电子邮件。该程序有效,我收到了电子邮件但是当我查看发送的电子邮件时(因为我自己发送来自同一帐户的电子邮件),它表示没有收件人或“收件人:”地址,只有一个密件抄送地址我希望将电子邮件发送给。这是smtplib的一个特性 - 它实际上并没有添加'To:'地址,只有Bcc地址?代码如下:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example@gmail.com"
toAddr = "example@gmail.com"
msg = ""
# smtp login
username = "example@gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
答案 0 :(得分:1)
按如下方式更新代码可以解决问题:
if (old_source != new_source):
# now we create a mesasge to send via email
fromAddr = "example@gmail.com"
toAddr = "example@gmail.com"
msg = ""
# smtp login
username = "example@gmail.com"
pswd = "password"
# create server object and login to the gmail smtp
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
header = 'To:' + toAddr + '\n' + 'From: ' + fromAddr + '\n' + 'Subject:testing \n'
msg = header + msg
server.login(username, pswd)
server.sendmail(fromAddr, toAddr, msg)
server.quit()
答案 1 :(得分:0)
尝试手动将任何标题添加到邮件中,并通过空白行与主体分隔,例如:
...
msg="""From: sender@domain.org
To: recipient@otherdomain.org
Subject: Test mail
Mail body, ..."""
...
答案 2 :(得分:0)
试试这个,似乎对我有用。
#!/usr/bin/python
#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
sender = 'example@gmail.com'
receivers = ['example@gmail.com']
msg = MIMEMultipart()
msg['From'] = 'example@gmail.com'
msg['To'] = 'example@gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))
ServerConnect = False
try:
smtp_server = SMTP('smtp.gmail.com','465')
smtp_server.login('#####@gmail.com', '############')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
if ServerConnect == True:
try:
smtp_server.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except SMTPException as e:
print "Error: unable to send email", e
finally:
smtp_server.close()
答案 3 :(得分:0)
将它扔出去:请尝试menu with tabs。免责声明:我是维护者,但我觉得它可以帮助所有人!
它确实提供了很多默认设置:我非常确定您能够直接发送电子邮件:
import yagmail
yag = yagmail.SMTP(username, password)
yag.send(to_addrs, contents = msg)
还将设置标题:)
您必须首先使用以下任一方式安装yagmail
:
pip install yagmail # python 2
pip3 install yagmail # python 3
一旦你想要嵌入html /图像或添加附件,你真的喜欢这个包!
它还可以防止您在代码中输入密码,从而使其更加安全。