简体   繁体   English

Gmail 的 SMTP 发送电子邮件问题

[英]SMTP Sending e-mail issue with Gmail

I have a script that sends a .png file with SMTP.我有一个使用 SMTP 发送 .png 文件的脚本。 When I use a hotmail account;当我使用 hotmail 帐户时;

smtplib.SMTP('smtp.live.com', 587)

It works without any problem.它可以毫无问题地工作。 But when I use a gmail account;但是当我使用 gmail 帐户时;

smtplib.SMTP('smtp.gmail.com', 587)

An error raises: SMTPServerDisconnected: Connection unexpectedly closed引发错误: SMTPServerDisconnected: Connection unexpectedly closed

I've changed smtplib.SMTP('smtp.gmail.com', 587) to smtplib.SMTP('localhost') but didn't work.我已将smtplib.SMTP('smtp.gmail.com', 587)更改为smtplib.SMTP('localhost')但没有用。 How can I fix this gmail problem?我该如何解决这个 gmail 问题?

Try this code,its working fine for me,试试这个代码,它对我来说很好用,

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()

you can user smtplib and email for sending emails, this code working for me after i follow this steps.您可以使用 smtplib 和电子邮件来发送电子邮件,在我按照以下步骤操作后,此代码对我有用。

steps are步骤是

  1. Sign in to Gmail.登录 Gmail。
  2. Click the gear in the top right .单击右上角的齿轮。
  3. Select Settings.选择设置。
  4. Click Forwarding and POP/IMAP.单击转发和 POP/IMAP。
  5. Select Enable IMAP.选择启用 IMAP。 6.Click Save Changes 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM