【发布时间】:2018-06-30 09:42:38
【问题描述】:
这是我在这里的第一篇文章 :) 这是我制作的第一条蟒蛇。 我正在尝试编写一个在运行时发送电子邮件的脚本。 关于这封电子邮件,对我来说有 3 件重要的事情:
1) 没有“收件人”,只有“抄送”和“密件抄送”。
2) 密件抄送 - 密件抄送下有很多地址,所有地址都必须收到邮件,但其他邮件地址必须隐藏。
3) 我想为一个词添加一个超链接。
我曾尝试使用 MIMEMultipart,但我找不到让 BCC 按我的意愿工作的方法(我翻遍了 google 和 stackoverflow,但无法让它工作)。 我能够实现发送带有隐藏密件抄送的电子邮件以按我的意愿工作,但它没有使用 MIMEMultipart - 仅使用 smtplib,但我似乎无法理解如何集成 html 部分。
def send_email():
password = '*********'
bcc = ['danielofir8@gmail.com','danielofirpython@gmail.com']
from_addr = 'danielofirsales@gmail.com'
to_addr = ''
cc_addr = 'danielofirsales@gmail.com'
mail_subject = "Testing E-mail"
content = "Maintenance on the New York data center will be performed on Sunday, July 1st, 2018 at 06:30 UTC.\nWe expect to complete the maintenance by Sunday, July 1st, 2018 at 08:30 "
body = f"From: {from_addr}\r\n" + f"To: {to_addr}\r\n" + f"Cc: {cc_addr}\r\n" + f"Subject: {mail_subject}\r\n" + "\r\n" + content
to_addr = [to_addr] + [cc_addr] + bcc
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('danielofirsales@gmail.com',password)
server.sendmail(from_addr, to_addr ,body)
server.quit()
print("Success")
except:
print("Failed")
send_email()
我发现有人在这里写了一段关于如何使用 MIMEMultipart 在电子邮件中发送 HTML 的代码,并且能够发送带有超链接的电子邮件,但是每次尝试添加 BCC(我发现了几种不同的方式在线),我得到一个错误。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
password = '*******'
from_adr='danielofirsales@gmail.com'
to_adr='danielofirpython@gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Emailing a link"
msg['From'] = 'danielofirsales@gmail.com'
msg['To'] = 'danielofirpython@gmail.com'
html = """
<html>
<head></head>
<body>
<p>Maintenance on the New York data center will be performed on Sunday, July 1st, 2018 at 06:30 UTC.\nAs published on our
<a href="http://www.google.com">Status Page</a> - We expect to complete the maintenance by Sunday, July 1st, 2018 at 08:30</p>
</body>
</html>
"""
part1=MIMEText(html, 'html')
part2=MIMEText("Maintenance on the New York data center will be performed on Sunday, July 1st, 2018 at 06:30 UTC.\nAs published on our http://www.google.com - We expect to complete the maintenance by Sunday, July 1st, 2018 at 08:30", 'text')
msg.attach(part1)
msg.attach(part2)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('danielofirsales@gmail.com',password)
server.sendmail(msg['From'], msg['To'] ,msg.as_string())
server.quit()
print("Success")
有没有办法使用 smtplib 的隐藏密件抄送选项和 MIMEMultipart 的 html 选项?
同样重要的是,目前脚本应该通过Gmail发送电子邮件,但实际应用时它会从公司的电子邮件服务器发送电子邮件。
感谢您的帮助:)
丹尼尔。
【问题讨论】:
-
非常抱歉,我刚刚发布了我的解决方案。
-
谢谢!我删除了我的评论:)
标签: html hyperlink hidden smtplib bcc