使用Gmail使用python发送电子邮件

时间:2017-04-27 19:58:59

标签: python email

我编写了一个python脚本,用于将电子邮件从我的Gmail帐户发送到另一封电子邮件。代码是:

import smtplib
fromaddr = 'my@gmail.com'
toaddrs  = 'to@gmail.com'

msg = 'my message'

username = 'my@gmail.com'
password = 'myPass'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
print("Done")

我正在发送电子邮件时收到“完成”输出。但问题是:我似乎无法收到电子邮件。它不会显示在收件箱中。我找不到问题:(任何人都可以帮忙吗?

提前致谢...

2 个答案:

答案 0 :(得分:4)

检查一下,这对我来说非常有用......

def send_mail(self):
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText

    gmailUser = 'myemail@gmail.com'
    gmailPassword = 'P@ssw0rd'
    recipient = 'sendto@gmail.com'
    message='your message here '

    msg = MIMEMultipart()
    msg['From'] = gmailUser
    msg['To'] = recipient
    msg['Subject'] = "Subject of the email"
    msg.attach(MIMEText(message))

    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()

答案 1 :(得分:0)

在您的gmail帐户上启用less secure apps并供Python3使用:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmailUser = 'XXXXX@gmail.com'
gmailPassword = 'XXXXX'
recipient = 'XXXXX@gmail.com'

message = f"""
Your message here...
"""

msg = MIMEMultipart()
msg['From'] = f'"Your Name" <{gmailUser}>'
msg['To'] = recipient
msg['Subject'] = "Your Subject..."
msg.attach(MIMEText(message))

try:
    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()
    print ('Email sent!')
except:
    print ('Something went wrong...')