Python SMTP/MIME邮件正文

2024-04-29 14:04:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经工作了2天了,并设法得到了这个脚本与一个pcapng文件附加发送,但我似乎无法使邮件正文出现在电子邮件。在

import smtplib
import base64
import ConfigParser
#from email.MIMEapplication import MIMEApplication
#from email.MIMEmultipart import MIMEMultipart
#from email.MIMEtext import MIMEText
#from email.utils import COMMASPACE, formatdate

Config = ConfigParser.ConfigParser()
Config.read('mailsend.ini')

filename = "test.pcapng"

fo = open(filename, "rb")
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent)  # base 64

sender = 'notareal@email.com'  # raw_input("Sender: ")
receiver = 'someother@fakeemail.com'  # raw_input("Recipient: ")

marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")

body ="""
This is a test email to send an attachment.
"""

# Define the main headers
header = """ From: From Person <notareal@email.com>
To: To Person <someother@fakeemail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define message action
message_action = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body, marker)

# Define the attachment section
message_attachment = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" % (filename, filename, encoded_content, marker)

message = header + message_action + message_attachment

try:
    smtpObj = smtplib.SMTP('smtp.gmail.com')
    smtpObj.sendmail(sender, receiver, message)
    print "Successfully sent email!"
except Exception:
    print "Error: unable to send email"

我的目标是最终让这个脚本在从配置文件中读取参数后发送电子邮件,并附加一个pcapng文件以及描述wireshark事件的其他文本数据。电子邮件在发送时不显示邮件正文。pcapng文件目前只是一个充满假IP和子网的测试文件。我的邮件正文哪里出了问题?在

^{pr2}$

这是我的第二次尝试,所有的“ms_…”变量都是通过一个更大的程序全局的。在


Tags: 文件fromimportcommessageinputattachment电子邮件
2条回答

你不应该重新发明轮子。使用Python包含在标准库中的mime模块,而不是自己创建头。我还没能测试出来,但看看这个是否有效:

import smtplib
import base64
import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

filename = "test.pcapng"

with open(filename, 'rb') as fo:
    filecontent = fo.read()
    encoded_content = base64.b64encode(filecontent)

sender = 'notareal@email.com'  # raw_input("Sender: ")
receiver = 'someother@fakeemail.com'  # raw_input("Recipient: ")

marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")

body ="""
This is a test email to send an attachment.
"""

message = MIMEMultipart(
    From=sender,
    To=receiver,
    Subject='Sending Attachment')

message.attach(MIMEText(body))          # body of the email

message.attach(MIMEApplication(
    encoded_content,
    Content_Disposition='attachment; filename="{0}"'.format(filename))  # b64 encoded file
    )

try:
    smtpObj = smtplib.SMTP('smtp.gmail.com')
    smtpObj.sendmail(sender, receiver, message)
    print "Successfully sent email!"
except Exception:
    print "Error: unable to send email"

我省略了一些部分(比如ConfigParser变量),只演示了与电子邮件相关的部分。在

参考文献:

How to send email attachments with Python

通过添加ConfigParser解决了这个问题。对于.ini文件,这是完全可以使用的

import smtplib
####import sys#### duplicate
from email.parser import Parser
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import ConfigParser


def mail_man(cfg_file, event_file):
    # Parse email configs from cfg file
    Config = ConfigParser.ConfigParser()
    Config.read(str(cfg_file))

    mail_man_start = Config.get('DC_MS', 'ms')
    security = Config.get('DC_MS', 'ms_security')
    add_attachment = Config.get('DC_MS', 'ms_attach')
    try:
        if mail_man_start == "y" or mail_man_start == "Y":
            fromaddr = Config.get("DC_MS", "ms_from")
            addresses = [Config.get("DC_MS", "ms_sendto")] + [Config.get("DC_MS", "ms_cc")] + [Config.get("DC_MS", "ms_bcc")]

            msg = MIMEMultipart()  # creates multipart email
            msg['Subject'] = Config.get('DC_MS', 'ms_subject')  # sets up the header
            msg['From'] = Config.get('DC_MS', 'ms_from')
            msg['To'] = Config.get('DC_MS', 'ms_sendto')
            msg['reply-to'] = Config.get('DC_MS', 'ms_replyto')
            msg['X-Priority'] = Config.get('DC_MS', 'ms_importance')
            msg['CC'] = Config.get('DC_MS', 'ms_cc')
            msg['BCC'] = Config.get('DC_MS', 'ms_bcc')
            msg['Return-Receipt-To'] = Config.get('DC_MS', 'ms_rrr')
            msg.preamble = 'Event Notification'

            message = '... use this to add a body to the email detailing event. dumpcap.py location??'
            msg.attach(MIMEText(message))   # attaches body to email

            # Adds attachment if ms_attach = Y/y
            if add_attachment == "y" or add_attachment == "Y":
                attachment = open(event_file, "rb")
                # Encodes the attachment and adds it to the email
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())
                encoders.encode_base64(part)
                part.add_header('Content-Disposition', "attachment; filename = %s" % event_file)

                msg.attach(part)
            else:
                print "No attachment sent."

            server = smtplib.SMTP(Config.get('DC_MS', 'ms_smtp_server'), Config.get('DC_MS', 'ms_smtp_port'))
            server.ehlo()
            server.starttls()
            if security == "y" or security == "Y":
                server.login(Config.get('DC_MS', 'ms_user'), Config.get('DC_MS', 'ms_password'))
            text = msg.as_string()
            max_size = Config.get('DC_MS', 'ms_maxattach')
            msg_size = sys.getsizeof(msg)
            if msg_size <= max_size:
                server.sendmail(fromaddr, addresses, text)
            else:
                print "Your message exceeds maximum attachment size.\n Please Try again"
            server.quit()
            attachment.close()
        else:
            print "Mail_man not activated"
    except:
       print "Error! Something went wrong with Mail Man. Please try again."

相关问题 更多 >