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



我用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()已经被调用,但我想用新的文本替换正文,有一种方法吗?

如果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")

如果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在他的答案中所做的那样。

相关内容

最新更新