【问题标题】:Sending an email containing HTML code using python使用 python 发送包含 HTML 代码的电子邮件
【发布时间】:2016-12-13 16:49:22
【问题描述】:

我正在尝试编写一个 python 脚本,它将 html 代码从我的邮件 ID 发送到目标邮件 ID。

内容如下:

import smtplib

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

me = "prudhvi@domainname.com"
you = "aditya@domainname.com"

msg = MIMEMultipart('multipart')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

html = """\
<html>
 <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>       
    </p>
  </body>
</html>
"""

part = MIMEText(html, 'html')

msg.attach(part)

s = smtplib.SMTP('localhost')

s.sendmail(me, you, msg.as_string())
s.quit()

我尝试运行它并遇到了这个错误:

Traceback (most recent call last):
  File "C:/Users/admin/Desktop/samp.py", line 29, in <module>
    s = smtplib.SMTP('localhost')
  File "C:\Python27\Lib\smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Python27\Lib\smtplib.py", line 316, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python27\Lib\smtplib.py", line 291, in _get_socket
    return socket.create_connection((host, port), timeout)
  File "C:\Python27\Lib\socket.py", line 575, in create_connection
    raise err
error: [Errno 10061] No connection could be made because the target machine actively refused it

我能知道我哪里出错了吗?

【问题讨论】:

  • smtplib.SMTP('localhost') - 您需要连接到电子邮件服务器。这会尝试连接到本地计算机上的电子邮件服务器。请尝试使用真正的电子邮件服务器。您可能需要登录。
  • @dawidferenczy - 我认为这太笼统了,不能重复。 OP 只需要登录到电子邮件服务器。
  • 我会在您的机器上正确设置 SMTP 服务器,或者按照 tdelaney 的建议,使用其他一些 SMTP 服务器(如 Google 等),但在这种情况下,您必须在那里授权,并且电子邮件的发件人将设置为您用于身份验证的帐户。
  • @tdelaney 该死的,你是对的,我使用了错误的链接,我想使用以下内容:stackoverflow.com/questions/37960035/…

标签: python email


【解决方案1】:

我通过执行以下操作解决了我的问题:

1.) 提供用户名和密码。 2.) 将google的低安全设置为ON。

代码:

import smtplib

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

me = "prudhvir36@gmail.com"
you = "prudhvi.g@domainname.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

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

mail.ehlo()

mail.starttls()

mail.login('prudhvir36', '*************')
mail.sendmail(me, you, msg.as_string())
mail.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2016-11-23
    • 2012-01-06
    • 2013-04-01
    • 1970-01-01
    • 2010-10-27
    相关资源
    最近更新 更多