Cú pháp try... except trong python

mọi người cho em hỏi câu lênh try…except trong python nó được dùng như thế nào với ạ e chưa hiểu nó hoạt động như thế nào nữa. ví dụ như trong code này thì nó hoạt động như thế nào vậy ạ nhận tiện cho e hỏi là code này sai ở đâu mà e chạy k ra ạ. E xin cảm ơn

#!/usr/bin/python

import smtplib
import base64
filename = "/tmp/test.txt"
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)#base64

sender = '[email protected]'
reciever = '[email protected]'

marker = "AUNIQUEMARKER"

body="""
This is a test email to send an attachement.
"""
#Define the main headers.
part1 = """From: From Person
To: To Person
Subject:Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed;boundary=%s
-%s
"""%(marker,marker)

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

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

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

%s 
-%s-
"""%(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
	smtpObj=smtplib.SMTP('localhost')
	smtpObj.sendmail(sender, reciever, message)
	print("Successfully sent email")
except Exception:
	print("Error: unable to send email")

Thì nếu try đúng nó chạy try ,k thì chạy cái excep ra ,m k để gì thì nó báo lỗi :smile:

Mà theo e đọc thì cái open nó chỉ có 3 cái là r,a,w thôi chứ nhỉ là gì có rb đâu ,sai mong bỏ qua ạ

à theo mình biết thì nó có nhiều lắm bạn gần chục cái cơ

Dòng print("Error: unable to send email") chạy khi cục này bị lỗi :smile:

	smtpObj=smtplib.SMTP('localhost')
	smtpObj.sendmail(sender, reciever, message)
	print("Successfully sent email")

Tốt nhất là bạn up cái ảnh chụp màn hình lên + thông báo lỗi để mọi người giúp, chứ thường mọi người cũng lười bật máy lên chạy code của bạn lắm :sweat_smile:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?