我們試圖發送帶有附件的電子郵件,但由於某些原因,附件不會顯示給使用Outlook的用戶。當通過python發送附件時不會在Outlook中顯示
如果他們轉發電子郵件給使用gmail的人,它在gmail中顯示正常。
如果gmail用戶將電子郵件轉發給outlook用戶,它會在outlook中顯示(可能是因爲gmail重新生成郵件)。
這是我們用來發送電子郵件的代碼:
def send_email(headers={}, attachments=[], body={}):
ADDRESS_HEADERS = set(['from', 'to', 'cc', 'bcc', 'reply-to'])
msg = MIMEMultipart('alternative')
msg.preamble = "You need a MIME-aware email client to read this email.\n"
def add_headers():
def encode_address(v):
(name, address) = parseaddr(v)
name = str(Header(unicode(name), 'utf-8'))
address = address.encode('ascii')
return formataddr((name, address))
for key, value in headers.iteritems():
if not isinstance(value, list):
value = [value]
if key.lower() in ADDRESS_HEADERS:
value = map(encode_address, value)
msg[key.title()] = u';'.join(value)
def set_body():
msg.attach(MIMEText(body.get('text', ''), 'plain', _charset='utf-8'))
if 'html' in body:
msg.attach(MIMEText(body['html'], 'html', _charset='utf-8'))
def attach_file(attachment):
maintype, subtype = attachment['mimetype'].split("/", 1)
part = MIMEBase(maintype, subtype)
filename = attachment['filename']
name = attachment.get('name', os.path.basename(filename))
with open(filename, 'rb') as f:
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=name)
msg.attach(part)
add_headers()
map(attach_file, attachments)
set_body()
composed = msg.as_string()
p = subprocess.Popen("sendmail -t", shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
(stdout, stderr) = p.communicate(composed)
if p.returncode != 0:
raise IOError(u'{}\n\n{}'.format(stdout, stderr).strip())
這是非常難找到任何相關信息,由於電子郵件實現的碎片。
我們要附加的文件是出類拔萃的MIME類型application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
我試圖找到正在使用的Outlook版本的詳細信息的文件。
'part.add_header('Content-Disposition','attachment',filename = name)'應該和你寫的一樣。我會嘗試概括MIME類型。 – 2013-05-01 17:21:10
我在使用'part = MIMEBase('application','vnd.openxmlformats-officedocument.spreadsheetml.sheet')時也遇到了問題。 IMO'part = MIMEBase('application',「octet-stream」)'適用於任何類型 – jes516 2015-07-29 15:28:26