使用python发送包含HTML代码的电子邮件

时间:2016-12-13 16:49:22

标签: python email

我正在尝试编写一个python脚本,它将我的邮件ID中的html代码发送到目标邮件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

我能知道我哪里出错吗?

1 个答案:

答案 0 :(得分:0)

我通过以下方式解决了我的问题:

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