SMTP使用Gmail发送电子邮件问题

问题描述 投票:0回答:2

我有一个脚本,用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问题?

python smtp gmail python-3.4 smtplib
2个回答
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()

0
投票

您可以使用smtplib和电子邮件发送电子邮件,此代码在我按照此步骤后为我工作。

步骤是

  1. 登录Gmail。
  2. 单击右上角的齿轮。
  3. 选择设置。
  4. 单击“转发”和“POP / IMAP”。
  5. 选择“启用IMAP”。 6.单击“保存更改”

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()
© www.soinside.com 2019 - 2024. All rights reserved.