2012-05-31 2 views
0

Python 2.7을 사용하여 첨부 파일이 포함 된 전자 메일을 보내려고합니다. 모든 내용은 이메일에 첨부 된 0 K의 첨부 파일 내용을 제외하고 모두 작동합니다.Python 전자 메일 첨부 파일이 비어 있습니다.

인코딩에 문제가 있습니까?

def sendMail(subject, text, *attachmentFilePaths): 
    gmailUser = USER 
    gmailPassword = PASSWORD 
    recipient = RECIPIENT 

    msg = MIMEMultipart() 
    msg['From'] = gmailUser 
    msg['To'] = recipient 
    msg['Subject'] = subject 
    msg.attach(MIMEText(text)) 

    for attachmentFilePath in attachmentFilePaths: 
     msg.attach(getAttachment(attachmentFilePath)) 

    mailServer = smtplib.SMTP('smtp.gmail.com', 587) 
    mailServer.ehlo() 
    mailServer.starttls() 
    mailServer.ehlo() 
    mailServer.login(gmailUser, gmailPassword) 
    mailServer.sendmail(gmailUser, recipient, msg.as_string()) 
    mailServer.close() 

    print('Sent email to %s' % recipient) 

def getAttachment(attachmentFilePath): 
    contentType, encoding = mimetypes.guess_type(attachmentFilePath) 

    if contentType is None or encoding is not None: 
     contentType = 'application/octet-stream' 
    mainType, subType = contentType.split('/', 1) 
    file = open(attachmentFilePath, 'rb') 

    if mainType == 'text': 
     attachment = MIMEText(file.read()) 
    elif mainType == 'message': 
     attachment = email.message_from_file(file) 
    elif mainType == 'image': 
     attachment = MIMEImage(file.read(),_subType=subType) 
    elif mainType == 'audio': 
     attachment = MIMEAudio(file.read(),_subType=subType) 
    else: 
     attachment = MIMEBase(mainType, subType) 

    attachment.set_payload(file.read()) 
    encode_base64(attachment) 
    file.close() 
    attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) 
    return attachment 
+0

버그에 대한 'getAttachment' 함수를 테스트하십시오. – Blender

+0

좀 더 구체적으로 기재 할 수 있습니까? 나는 전자 메일 모듈에 관한 초보자이기 때문에 어디에서 시작해야하는지 정확히 알지 못합니다. –

+0

버그가있는 곳을 찾으십시오. 어떤 기능이 그 기능을 수행하지 못하고 있습니까? – Blender

답변

1

이 당신의 문제 : 파일이 이미 읽은 되었기 때문에 else를 제외하고는 항상 빈 문자열로 페이로드를 대체 할 것이라는 점을 의미

if mainType == 'text': 
    attachment = MIMEText(file.read())      # <- read file 
elif mainType == 'message': 
    attachment = email.message_from_file(file)    # <- read file 
elif mainType == 'image': 
    attachment = MIMEImage(file.read(),_subType=subType) # <- read file 
elif mainType == 'audio': 
    attachment = MIMEAudio(file.read(),_subType=subType) # <- read file 
else: 
    attachment = MIMEBase(mainType, subType) 

attachment.set_payload(file.read())   # <- re-read file ! 

.

+0

고마워요! 나는 매번 페이로드를 설정하지 않아도된다는 것을 깨닫지 못했습니다. –

관련 문제