python - 应该最终返回外部并且异常处理是否完美?

标签 python exception smtp smtplib

我不应该把下面这个方法的返回值放在finally中吗? Pylint 给出了这句话的错误: 3:finally block 中的 return 语句可能会吞噬异常(丢失异常)

def sendMessage(self, subject, msgContent, files, mailto):
    """ Send the email message

        Args:
            subject(string): subject for the email
            msgContent(string): email message Content
            files(List): list of files to be attached
            mailto(string): email address to be sent to
    """

    msg = self.prepareMail(subject, msgContent, files, mailto)

    # connect to server and send email
    server=smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT)
    server.ehlo()
    # use encrypted SSL mode
    server.starttls()
    # to make starttls work
    server.ehlo()
    server.login(self.usrname, self.password)
    server.set_debuglevel(self.debug)
    try:
        failed = server.sendmail(self.mailFrom, mailto, msg.as_string())
    except Exception as er:
        print er
    finally:
        server.quit()
        if failed:
            return False
        return True

最佳答案

好吧,我解决了问题,@Nabla 指出了右边!!

def sendMessage(self, subject, msgContent, files, mailto):
    """ Send the email message

        Args:
            subject(string): subject for the email
            msgContent(string): email message Content
            files(List): list of files to be attached
            mailto(string): email address to be sent to
    """

    msg = self.prepareMail(subject, msgContent, files, mailto)

    # connect to server and send email
    server = smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT)
    server.ehlo()
    # use encrypted SSL mode
    server.starttls()
    # to make starttls work
    server.ehlo()
    server.login(self.usrname, self.password)
    server.set_debuglevel(self.debug)
    try:
        server.sendmail(self.mailFrom, mailto, msg.as_string())
    except Exception as er:
        print er
        return False
    finally:
        server.quit()
    return True

关于python - 应该最终返回外部并且异常处理是否完美?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21808107/

相关文章:

c# - 如何使用 C# 通过 Gmail 发送电子邮件

java - Spring 集成 : SMTP server

Python我有设备ID如何获取设备地址

c# - XML模式

spring-boot - 如何将 ConstraintViolationException 500 错误转换为 400 错误请求?

c++ - 如何知道 std::exception 的异常类型

linq - 当 IQueryable 没有返回记录时 ToList() 抛出异常

python - Django Crispy Multichoices Form (Foreignkey) 正在打印 "Object"而不是 Object.name

python-linkedin api - 我该如何使用它?

python - Google App Engine mail.Send 在 python2.7/smtplib.py 中返回 "TypeError: unhashable instance"