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

标签 python email

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

import smtplib
fromaddr = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3beaa93b4beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>'
toaddrs  = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b200f28222e2623612c2022" rel="noreferrer noopener nofollow">[email protected]</a>'

msg = 'my message'

username = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38e9aa3848e828a8fcd808c8e" rel="noreferrer noopener nofollow">[email protected]</a>'
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")

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

提前致谢...

最佳答案

看看这个,这对我来说非常有用......

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

    gmailUser = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3954405c54585055795e54585055175a5654" rel="noreferrer noopener nofollow">[email protected]</a>'
    gmailPassword = 'P@ssw0rd'
    recipient = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c6d0dbd1c1daf5d2d8d4dcd99bd6dad8" rel="noreferrer noopener nofollow">[email protected]</a>'
    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()

关于python - 使用Python使用Gmail发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666912/

相关文章:

java - 用于从 Java 应用程序可靠地发送电子邮件的库 - 具有缓冲、重试等功能

python - 我想使用 Python 3 将目录上的所有 .txt 文件重命名为 .csv

Python函数出现异常时返回1

python - Google App Engine Python python 电子邮件无法正常工作

javascript - 我从我网站上的评论表单中收到空电子邮件

php - Yii 2 : Unable to send log via mail

python - 查找与条件匹配的第一个序列项

python - 删除跨越 xml 树分支的 2 个标签之间的所有内容

python - 合并两个字符串列表

ruby-on-rails-3 - 带有 Rails 3 和 Heroku Net::SMTPSyntaxError 的电子邮件:501 语法错误