使用Python编写发送电子邮件的代码
解析: 1. 首先,我们需要导入Python的内置库smtplib和email.mime.text,这两个库可以帮助我们发送电子邮件。 2. 然后,我们需要设置SMTP服务器的地址和端口,以及发送者的邮箱地址和密码。 3. 接下来,我们需要创建一个MIMEText对象,这个对象包含了我们要发送的电子邮件的内容。 4. 然后,我们需要创建一个SMTP对象,并使用它来连接到SMTP服务器。 5. 接着,我们需要使用SMTP对象的sendmail方法来发送电子邮件。 6. 最后,我们需要关闭SMTP连接。 代码如下: ```python import smtplib from email.mime.text import MIMEText # 设置SMTP服务器地址和端口 smtp_server = 'smtp.example.com' smtp_port = 587 # 设置发送者邮箱地址和密码
importsmtplibfromemail.mime.textimportMIMETextfromemail.mime.multipartimportMIMEMultipartfromemail.mime.applicationimportMIMEApplicationfromemail.headerimportHeaderfromemail.utilsimportparseaddr,formataddrimportmimetypesimportosdefsend_email(smtp_server,username,password,sender,recipients,subject,content,cc,bcc,port=25,sendername=None,attachments=None):def_format_addr(s):name,addr=parseaddr(s)returnformataddr((Header(name,'utf-8').encode(),addr))ifnotattachments:attachments=[]msg=MIMEMultipart()ifsendername:msg['From']=_format_addr(sendername+'<%s>'%sender)else:msg['From']=senderifisinstance(recipients,str):recipients=[recipients]msg['To']=",".join(recipients)ifcc:ifisinstance(cc,str):cc=[cc]cc_list=[addrforaddrinccifaddrnotinrecipients]ifcc_list:msg['Cc']=",".join(cc_list)recipients+=cc_listifbcc:ifisinstance(bcc,str):bcc=[bcc]bcc_list=[addrforaddrinbccifaddrnotinrecipients]ifbcc_list:msg['Bcc']=",".join(bcc_list)recipients+=bcc_listmsg['Subject']=Header(subject,'utf-8').encode()text_part=MIMEText(content,'html','utf-8')msg.attach(text_part)forattachmentinattachments:file_path=attachment["path"]ifnotos.path.isfile(file_path):print("附件文件不存在:{}".format(file_path))continuetry:withopen(file_path,"rb")asf:mime_type,encoding=mimetypes.guess_type(file_path)ifmime_typeisNone:mime_type='application/octet-stream'part=MIMEApplication(f.read())part.add_header('Content-Disposition','attachment',filename=attachment["filename"])part.add_header('Content-Type',mime_type)msg.attach(part)exceptFileNotFoundErrorase:print("文件未找到:{}".format(e))exceptExceptionase:print("附件读取失败:{}".format(e))try:ifstr(port)=="25":server=smtplib.SMTP(smtp_server,port)else:server=smtplib.SMTP_SSL(smtp_server,port)server.login(username,password)server.sendmail(sender,recipients,msg.as_string())server.quit()print("邮件发送成功!")exceptExceptionase:print("邮件发送失败:{}".format(e))smtp_server="smtp.aliyun.com"username="abc@aliyun.com"password="password"sender="abc@aliyun.com"recipients="abc@abc.cn"cc=["abc@126.com","abc@139.com"]bcc=""subject="title"content="content"n="name"port=25attachments=[{"filename":"申请单.xlsx","path":"C:/申请单.xlsx"},{"filename":"新课标.docx","path":"D:/新课标.docx"},{"filename":"笨笨狗.pdf","path":"D:/books/笨笨狗.pdf"}]send_email(smtp_server,username,password,sender,recipients,subject,content,cc,bcc,port=port,sendername=n,attachments=attachments)