Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python发送HTML电子邮件_Python_Email_Html Email - Fatal编程技术网

使用Python发送HTML电子邮件

使用Python发送HTML电子邮件,python,email,html-email,Python,Email,Html Email,如何使用Python在电子邮件中发送HTML内容?我可以发送简单文本。来自: 下面是一个示例,说明如何使用其他纯文本版本创建HTML消息: #/usr/bin/python 导入smtplib 从email.mime.multipart导入MIMEMultipart 从email.mime.text导入MIMEText #我==我的电子邮件地址 #您==收件人的电子邮件地址 我=”my@email.com" 你=”your@email.com" #创建消息容器-正确的MIME类型为multipa

如何使用Python在电子邮件中发送HTML内容?我可以发送简单文本。

来自:

下面是一个示例,说明如何使用其他纯文本版本创建HTML消息:

#/usr/bin/python
导入smtplib
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
#我==我的电子邮件地址
#您==收件人的电子邮件地址
我=”my@email.com"
你=”your@email.com"
#创建消息容器-正确的MIME类型为multipart/alternative。
msg=MIMEMultipart('alternative')
msg['Subject']=“链接”
msg['From']=我
msg['To']=您
#创建消息正文(纯文本和HTML版本)。
text=“Hi!\n您怎么样?\n您想要的链接是:\nhttp://www.python.org"
html=”“”\
嗨!
你好吗?
这是你想要的。

""" #记录这两部分的MIME类型-text/plain和text/html。 part1=MIMEText(文本“纯”) part2=MIMEText(html,'html') #将部件附加到消息容器中。 #根据RFC 2046,在本例中,多部分消息的最后一部分 #HTML消息是最好的首选。 附加信息(第1部分) 附加信息(第2部分) #通过本地SMTP服务器发送邮件。 s=smtplib.SMTP('localhost') #sendmail函数接受3个参数:发件人地址、收件人地址 #和要发送的消息-在这里它作为一个字符串发送。 s、 sendmail(我,你,msg.as_string()) s、 退出
以下是示例代码。这源于网站上的代码(找不到确切的链接)

def createhtmlmail(html、文本、主题、来自电子邮件):
“”“创建将以流行格式呈现HTML的mime消息。”
MUAs,以更好的方式发送文本“”
导入MIME编写器
进口美托尔
导入cStringIO
out=cStringIO.StringIO()#消息的输出缓冲区
htmlin=cStringIO.StringIO(html)
txtin=cStringIO.StringIO(文本)
writer=MimeWriter.MimeWriter(输出)
#
#设置一些基本标题。。。我们把主题放在这里
#因为smtplib.sendmail希望它位于
#消息体
#
writer.addheader(“From”,fromEmail)
writer.addheader(“主题”,主题)
writer.addheader(“MIME版本”、“1.0”)
#
#启动消息的多部分部分部分
#多部分/备选方案似乎效果更好
#在某些MUA上,而不是多部分/混合
#
编写者:startmultipartbody(“备选方案”)
writer.flushheaders()
#
#纯文本部分
#
子部分=编写者下一部分()
子部分.添加标题(“内容传输编码”,“引用可打印”)
pout=子部分。起始正文(“文本/普通”[(“字符集”,“美国ascii”))
mimetools.encode(txtin,pout,'quoted printable')
txtin.close()
#
#启动消息的html子部分
#
子部分=编写者下一部分()
子部分.添加标题(“内容传输编码”,“引用可打印”)
#
#返回一个可以写入的文件或对象
#
pout=子部分.startbody(“文本/html”[(“字符集”,“美国ascii”)]))
mimetools.encode(htmlin,pout,'quoted printable')
htmlin.close()
#
#现在,我们完成了,关闭我们的作家和
#返回消息正文
#
作者:最后一部分()
msg=out.getvalue()
结束
打印味精
返回消息
如果名称=“\uuuuu main\uuuuuuuu”:
导入smtplib
html='html版本'
text='测试版本'
主题=“备份报告”
message=createhtmlmail(html、文本、主题,“来自主机”)
server=smtplib.SMTP(“SMTP\服务器\地址”、“SMTP\端口”)
server.login('用户名','密码')
server.sendmail('sender@host.com', 'target@otherhost.com",留言)
server.quit()
您可以尝试使用我的模块

从mailer导入mailer
从邮件导入消息
消息=消息(发件人=”me@example.com",
To=”you@example.com")
message.Subject=“一封HTML电子邮件”
message.Html=“”嗨!
你好吗?
这是您想要的文件。

“”“ 发件人=Mailer('smtp.example.com') 发送者。发送(消息)
以下是公认答案的实现:

import smtplib

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

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
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>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()
导入smtplib
从email.mime.multipart导入MIMEMultipart
从email.mime.text导入MIMEText
#我==我的电子邮件地址
#您==收件人的电子邮件地址
我=”my@email.com"
你=”your@email.com"
#创建消息容器-正确的MIME类型为multipart/alternative。
msg=MIMEMultipart('alternative')
msg['Subject']=“链接”
msg['From']=我
msg['To']=您
#创建消息正文(纯文本和HTML版本)。
text=“Hi!\n您怎么样?\n您想要的链接是:\nhttp://www.python.org"
html=”“”\
嗨!
你好吗?
这是你想要的。

""" #记录这两部分的MIME类型-text/plain和text/html。 part1=MIMEText(文本“纯”) part2=MIMEText(html,'html') #将部件附加到消息容器中。 #根据RFC 2046,在本例中,多部分消息的最后一部分 #HTML消息是最好的首选。 附加信息(第1部分) 附加信息(第2部分) #通过本地SMTP服务器发送邮件。 mail=smtplib.SMTP('SMTP.gmail.com',587) mail.ehlo() mail.starttls() mail.login('用户名','密码') mail.sendmail(我,你,msg.as_string()) mail.quit()
以下是发送HTML电子邮件的简单方法,只需将内容类型标题指定为“text/HTML”:

import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = 'sender@test.com'
msg['To'] = 'recipient@test.com'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
        email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()
import email.message
导入smtplib
msg=email.message.message()
msg['Subject']='foo'
msg['From']='sender@test.com'
msg['To']='recipient@test.com'
msg.add_标题('Content-Type','text/html'))
msg.set_有效载荷('消息体')
#通过本地SMTP服务器发送邮件。
s=smtplib.SMTP('localhost')
s、 starttls()
s、 登录(电子邮件登录),
电子邮件(U passwd)
s、 sendmail(msg['From'],[msg['To']],msg.as_string())
s、 退出
实际上,我们采取了一种不同的方法

默认情况下,它将发送HTML,并为无法阅读电子邮件的读者提供自动回退功能。现在已经不是17世纪了

美国大学
import email.message
import smtplib

msg = email.message.Message()
msg['Subject'] = 'foo'
msg['From'] = 'sender@test.com'
msg['To'] = 'recipient@test.com'
msg.add_header('Content-Type','text/html')
msg.set_payload('Body of <b>message</b>')

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
s.starttls()
s.login(email_login,
        email_passwd)
s.sendmail(msg['From'], [msg['To']], msg.as_string())
s.quit()
import yagmail
yag = yagmail.SMTP("me@example.com", "mypassword")

html_msg = """<p>Hi!<br>
              How are you?<br>
              Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

yag.send("to@example.com", "the subject", html_msg)
    subject = "Hello"
    html = "<b>Hello Consumer</b>"

    client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",
                      aws_secret_access_key="your_secret")

client.send_email(
    Source='ACME <do-not-reply@acme.com>',
    Destination={'ToAddresses': [email]},
    Message={
        'Subject': {'Data': subject},
        'Body': {
            'Html': {'Data': html}
        }
    }
#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail(params, type_):
      email_subject = params['email_subject']
      email_from = "from_email@domain.com"
      email_to = params['email_to']
      email_cc = params.get('email_cc')
      email_bcc = params.get('email_bcc')
      email_body = params['email_body']

      msg = MIMEMultipart('alternative')
      msg['To'] = email_to
      msg['CC'] = email_cc
      msg['Subject'] = email_subject
      mt_html = MIMEText(email_body, type_)
      msg.attach(mt_html)

      server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
      server.set_debuglevel(1)
      toaddrs = [email_to] + [email_cc] + [email_bcc]
      server.sendmail(email_from, toaddrs, msg.as_string())
      server.quit()

# Calling the mailer functions
params = {
    'email_to': 'to_email@domain.com',
    'email_cc': 'cc_email@domain.com',
    'email_bcc': 'bcc_email@domain.com',
    'email_subject': 'Test message from python library',
    'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
    send_mail(params, t)
from O365 import Message

html_template =     """ 
            <html>
            <head>
                <title></title>
            </head>
            <body>
                    {}
            </body>
            </html>
        """

final_html_data = html_template.format(df.to_html(index=False))

o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final_html_data)
m.sendMessage()
```
import smtplib

FROM = "....@gmail.com"
TO = "another....@gmail.com"
SUBJECT= "Subject"
PWD = "thesecretkey"

TEXT="""
<h1>Hello</h1>
""" #Your Message (Even Supports HTML Directly)

message = f"Subject: {SUBJECT}\nFrom: {FROM}\nTo: {TO}\nContent-Type: text/html\n\n{TEXT}" #This is where the stuff happens

try:
    server=smtplib.SMTP("smtp.gmail.com",587)
    server.ehlo()
    server.starttls()
    server.login(FROM,PWD)
    server.sendmail(FROM,TO,message)
    server.close()
    print("Successfully sent the mail.")
except Exception as e:
    print("Failed to send the mail..", e)
```