繁体   English   中英

尝试从python发送电子邮件

[英]Trying to send email from python

我是python的新手,当尝试使用python发送邮件时,我的程序如下

import smtplib
from smtplib import SMTP

sender = 'raju.ab@gmail.com'
receivers = ['sudeer.p@eunoia.in']

message = """ this message sending from python
for testing purpose
"""

try:
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()
smtpObj.login(username,password)
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
print "Successfully sent email"
except smtplib.SMTPException:

打印“错误:无法发送电子邮件”

当我执行它时显示错误:无法发送电子邮件,如何在python中发送电子邮件,请解释

如此处所述: 如何使用Python以提供者身份通过Gmail发送电子邮件?

此代码有效。 但是GMAIL会警告您是否要允许此脚本发送电子邮件。 登录您的帐户,然后访问以下URL: https : //www.google.com/settings/security/lesssecureapps

import smtplib
gmail_user = "yourmail@gmail.com"
gmail_pwd = "mypassword"
FROM = 'yourmail@gmail.com'
TO = ['receiber@email.com'] #must be a list
SUBJECT = "Testing sending using gmail"
TEXT = "Testing sending mail using gmail servers"
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
  #server = smtplib.SMTP(SERVER) 
  server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
  server.ehlo()
  server.starttls()
  server.login(gmail_user, gmail_pwd)
  server.sendmail(FROM, TO, message)
  #server.quit()
  server.close()
  print 'successfully sent the mail'
except:
  print "failed to send mail"

我在代码中做了什么:

1,添加了一个错误对象以获取错误信息

import smtplib
from smtplib import SMTP       

try:
    sender = 'xxx@gmail.com'
    receivers = ['xxx.com']

    message = """ this message sending from python
    for testing purpose
    """
    smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.ehlo()
    smtpObj.login('xxx','xxx')
    smtpObj.sendmail(sender, receivers, message)
    smtpObj.quit()
    print "Successfully sent email"
except smtplib.SMTPException,error:
    print str(error)
    print "Error: unable to send email"

如果您运行此代码,您会看到一条错误消息,指出Google不允许您通过代码登录

gmail发生的变化:

1.登录gmail

2.转到此链接https://www.google.com/settings/security/lesssecureapps

3.单击启用,然后重试代码

希望对您有所帮助:)

但是,如果您启用它,则会存在安全威胁

暂无
暂无

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

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