使用python替换电子邮件的正文消息

时间:2015-09-17 17:21:21

标签: python email

我在python中创建了一个类,它将通过我的一个私人服务器发送电子邮件。它的工作原理,但我想知道是否有一种方法可以用新的方法替换现有的电子邮件正文消息?

电子邮件类

class Emailer:

  def __init__(self, subj=None, message=None, toAddr=None, attachment=None, image=None):
    # initialize email inputs

    self.msg = email.MIMEMultipart.MIMEMultipart()

    self.cidNum = 0

    self.message = []
    if message is not None:
        self.addToMessage(message,image)

    # set the subject of the email if there is one specified
    self.subj = []
    if subj is not None:
        self.setSubject(subj)

    # set the body of the email and any attachements specified
    self.attachment = []
    if attachment is not None:
        self.addAtachment(attachment)

    # set the recipient list
    self.toAddr = []
    if toAddr is not None:
        self.addRecipient(toAddr)

  def addAttachment(self,attachment):
    logger.debug("Adding attachement to email")
    # loop through list of attachments and add them to the email
    if attachment is not None:
        if type(attachment) is not list:
            attachment = [attachment]
        for f in attachment:
            part = email.MIMEBase.MIMEBase('application',"octet-stream")
            part.set_payload( open(f,"rb").read() )
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
            self.msg.attach(part)

  def addToMessage(self,message,image=None):
    logger.debug("Adding to email message. Content: [%s]" % message)
    # add the plain text message
    self.message.append(message) 
    # add embedded images to message
    if image is not None:
        if type(image) is not list:
            image = [image]
        for i in image:
            msgText = email.MIMEText.MIMEText('<br><img src="cid:image%s"><br>' % self.cidNum, 'html')   
            self.msg.attach(msgText)

            fp = open(i, 'rb')
            img = email.MIMEImage.MIMEImage(fp.read())
            fp.close()
            img.add_header('Content-ID','<image%s>' % self.cidNum)
            self.msg.attach(img)
            self.cidNum += 1

# method to set the subject of the email
  def setSubject(self,subj):
    self.msg['Subject'] = subj

# method to add recipients to the email
  def addRecipient(self, toAddr):
    # loop through recipient list
    for x in toAddr:
        self.msg['To'] = x

# method to configure server settings: the server host/port and the senders login info
  def configure(self,  serverLogin, serverPassword, fromAddr, toAddr, serverHost='myserver', serverPort=465):
    self.server=smtplib.SMTP_SSL(serverHost,serverPort) 
    self.server.set_debuglevel(True)
    # self.server.ehlo()
    # self.server.ehlo()
    self.server.login(serverLogin, serverPassword)  #login to senders email
    self.fromAddr = fromAddr
    self.toAddr = toAddr

# method to send the email
  def send(self):
    logger.debug("Sending email!")
    msgText = email.MIMEText.MIMEText("\n".join(self.message))
    self.msg.attach(msgText) 
    print "Sending email to %s " % self.toAddr
    text = self.msg.as_string() #conver the message contents to string format
    try:
        self.server.sendmail(self.fromAddr, self.toAddr, text)  #send the email
    except Exception as e:
        logger.error(e)

目前,addToMessage()方法是将文本添加到电子邮件正文的内容。如果已经调用了addToMessage()但是我想用新文本替换该正文,那么还有办法吗?

2 个答案:

答案 0 :(得分:2)

如果addToMessage()已被调用但我想用新文本替换该正文,有没有办法?

是。如果您始终替换添加到self.message的最后一个条目,则可以使用self.message[-1]引用此元素,因为它是一个列表。如果要替换特定元素,可以使用index()方法搜索它。

示例#1:替换正文中的最后一个书面文字

def replace_last_written_body_text(new_text):
    if len(self.message) > 0:
        self.message[-1] = new_text

示例#2:替换正文中的指定文字

def replace_specified_body_text(text_to_replace, new_text):
    index_of_text_to_replace = self.message.index(text_to_replace)
    if index_of_text_to_replace is not None:
        self.message[index_of_text_to_replace] = new_text
    else:
        logger.warning("Cannot replace non-existent body text")

答案 1 :(得分:1)

如果addToMessage只被调用过一次,那么:

message是一个列表,它的第一个元素是正文,因此您只需要用新文本替换该元素:

def replace_body(self, new_text):
    if len(self.message) > 0:
        self.message[0] = new_text
    else:
        self.message = [new_text]

我还没有测试过,但它应该可行。确保你为这个项目写了一些单元测试!

编辑: 如果多次调用addToMessage,那么新的替换函数可以替换整个文本,或者只替换它的一部分。如果您想要替换所有内容,则只需替换消息,例如上面else之后的部分:self.message = [new_text]。否则,你将不得不找到你需要替换的元素,就像@BobDylan在答案中所做的那样。