发送多封带有不同附件的电子邮件

huangapple go评论140阅读模式
英文:

Send multiple emails with different attachments each

问题

以下是代码的翻译部分:

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import smtplib, ssl
import os

dirname = r'C:\Path\To\Files'
ext = ('.txt', 'html')

for files in os.scandir(dirname):
    if files.path.endswith(ext):

        def sendmail():
            html_body = '''<html>
                <body>
                    <p style="font-size: 12;"><strong>Alert</strong><br>{html}</p>
                </body>
            </html>'''.format(html=html)

            subject = 'Text file content'
            senders_email = 'mail@mail.com'
            receiver_email = 'mail@mail.com'

            # 创建一个多部分消息并设置标题
            message = MIMEMultipart('alternative')
            message['From'] = senders_email
            message['To'] = receiver_email
            message['Subject'] = subject

            # 附加电子邮件正文
            message.attach(MIMEText(html_body, 'html'))

            # 要附加的文件名
            filename = 'signal.html'

            # 以二进制模式打开文件
            with open(filename, 'rb') as attachment:
                # 将文件添加为应用程序/八位字节流
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())

            # 将文件编码为ASCII字符以通过电子邮件发送
            encoders.encode_base64(part)

            # 将附件部分的标题添加为键/值对
            part.add_header(
                'Content-Disposition',
                f"attachment; filename= {filename}",
            )

            # 将附件添加到消息并将消息转换为字符串
            message.attach(part)
            text = message.as_string()

            # 使用安全连接登录到服务器
            context = ssl.create_default_context()
            with smtplib.SMTP("smtp.mail.com", 25) as server:
                # server.starttls(context=context)
                # server.login(senders_email, 'password')
                server.sendmail(senders_email, receiver_email, text)
            print("Email sent!")
        sendmail()

请注意,我保留了代码中的注释。

英文:

I have a list of text files and html files generated by two distinct functions. Each file is labeled signal1.txt, signal2, etc. and signal1.html, signal2.html, etc. I need to send an email with each file pair (signal1.txt and signal1.html, signal2.txt and signal.2.html, and so forth). I've tried several different ways, but I keep getting just one file pair attached (the last file number whatever it is). I have no problem sending one file type, but it gets messy when I try with two different files.

Any help is appreciated. The code is as follows.

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import smtplib, ssl
import os
dirname = r&#39;C:\Path\To\Files&#39;
ext = (&#39;.txt&#39;,&#39;html&#39;)
for files in os.scandir(dirname):
if files.path.endswith(ext):
def sendmail():
html_body = &#39;&#39;&#39;
&lt;html&gt;
&lt;body&gt;
&lt;p style=&quot;font-size: 12;&quot;&gt; &lt;strong&gt;Alert&lt;/strong&gt;&lt;br&gt;{html}&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
&#39;&#39;&#39;.format(html=html)
subject = f&#39;Text file content&#39;
senders_email = &#39;mail@mail.com&#39;
receiver_email = &#39;mail@mail.com&#39;
# Create a multipart message and set headers
message = MIMEMultipart(&#39;alternative&#39;)
message[&#39;From&#39;] = senders_email
message[&#39;To&#39;] = receiver_email
message[&#39;Subject&#39;] = subject
#Attach email body
message.attach(MIMEText(html_body, &#39;html&#39;))
# Name of the file to be attached
filename = f&#39;signal.html&#39;
# Open file in binary mode
with open(filename, &#39;rb&#39;) as attachment:
# Add file as application/octet-stream
part = MIMEBase(&#39;application&#39;, &#39;octet-stream&#39;)
part.set_payload(attachment.read())
# Encodes file in ASCII characters to send via email
encoders.encode_base64(part)
# Add header as key/value pair to attachment part
part.add_header(
&#39;Content-Disposition&#39;,
f&quot;attachment; filename= {filename}&quot;,
)
# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
# Log into server using secure connection
context = ssl.create_default_context()
with smtplib.SMTP(&quot;smtp.mail.com&quot;, 25) as server:
# server.starttls(context=context)
# server.login(senders_email, &#39;password&#39;)
server.sendmail(senders_email, receiver_email, text)
print(&quot;Email sent!&quot;)
sendmail()

答案1

得分: 1

我已经为您的问题修改了其中一个示例。这将所有文件放在一个电子邮件中:

# 导入 smtplib 以进行实际发送操作。
import smtplib

# 这里是我们需要的电子邮件包模块。
from email.message import EmailMessage

import os

dirname = 'C:\Path\To\Files'
ext = ('.txt', 'html')

msg = EmailMessage()
msg['Subject'] = '文本文件内容'
msg['From'] = 'mail@mail.com'
msg['To'] = 'mail@mail.com'

# 以二进制模式打开文件。您还可以省略子类型
# 如果要让 MIMEImage 猜测它。
for filename in os.scandir(dirname):
    if filename.path.endswith(ext):
        with open(filename, 'rb') as fp:
            data = fp.read()
            msg.add_attachment(data)

# 通过我们自己的 SMTP 服务器发送电子邮件。
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)
英文:

I've adapted one of these examples for your problem. This puts all the files in one email:

# Import smtplib for the actual sending function.
import smtplib
# Here are the email package modules we&#39;ll need.
from email.message import EmailMessage
import os
dirname = &#39;C:\Path\To\Files&#39;
ext = (&#39;.txt&#39;,&#39;html&#39;)
msg = EmailMessage()
msg[&#39;Subject&#39;] = &#39;Text file content&#39;
msg[&#39;From&#39;] = &#39;mail@mail.com&#39;
msg[&#39;To&#39;] = &#39;mail@mail.com&#39;
# Open the files in binary mode.  You can also omit the subtype
# if you want MIMEImage to guess it.
for filename in os.scandir(dirname):
if filename.path.endswith(ext):
with open(filename, &#39;rb&#39;) as fp:
data = fp.read()
msg.add_attachment(data)
# Send the email via our own SMTP server.
with smtplib.SMTP(&#39;localhost&#39;) as s:
s.send_message(msg)

答案2

得分: 0

以下是您要翻译的代码部分:

Found a way that worked using glob.

dirname = r'C:\Path\To\Files'
regex = create_txt_files(event_dict)
html_file = create_html_files(event_dict)

signalfiles = sorted(list(pathlib.Path(dirname).glob('*.txt')))
htmlfiles = sorted(list(pathlib.Path(dirname).glob('*.html')))

for i, path_html_file in enumerate(htmlfiles):
   sendmail(html_file[i], regex[i], path_html_file)
英文:

Found a way that worked using glob.

dirname = r&#39;C:\Path\To\Files&#39;
regex = create_txt_files(event_dict)
html_file = create_html_files(event_dict)
signalfiles = sorted(list(pathlib.Path(dirname).glob(&#39;*.txt&#39;)))
htmlfiles = sorted(list(pathlib.Path(dirname).glob(&#39;*.html&#39;)))
for i, path_html_file in enumerate(htmlfiles):
sendmail(html_file[i], regex[i], path_html_file)

huangapple
  • 本文由 发表于 2023年2月19日 15:28:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定