我有一个脚本,用SMTP发送.png文件。当我使用hotmail帐户时;
smtplib.SMTP('smtp.live.com', 587)
它没有任何问题。但是当我使用Gmail帐户时;
smtplib.SMTP('smtp.gmail.com', 587)
错误引发:SMTPServerDisconnected: Connection unexpectedly closed
我已将smtplib.SMTP('smtp.gmail.com', 587)
更改为smtplib.SMTP('localhost')
,但无法正常工作。我该如何修复这个gmail问题?
答案 0 :(得分:0)
试试这段代码,它对我来说很好,
import smtplib
## email sending function
def email_sender(input_message, email_to, client):
''' function to send email '''
to = email_to
gmail_user = '' ## email of sender account
gmail_pwd = '' ## password of sender account
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' +'Subject:site down! \n'
input_message = input_message + client
msg = header + input_message
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
答案 1 :(得分:0)
您可以使用smtplib和电子邮件发送电子邮件,此代码在我按照此步骤后为我工作。
步骤
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "your email"
my_password = r"your password"
you = "to email id"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
part2 = MIMEText(html, 'html')
msg.attach(part2)
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login(me, my_password)
s.sendmail(me, you, msg.as_string())
print s
s.quit()