2012-02-07 72 views
3

我試過用Gmail從python發送郵件,它工作正常。但問題是,當我使用一種方法創建Mail類時,我從該代碼發送特定的字符串,但無法發送。使用gmail發送郵件與python

class Mail: 
    def send_mail(self, msg): 
     import smtplib 

     fromaddr = '[email protected]' 
     toaddrs = '[email protected]' 
     msg = msg + "something" 

     print msg 

     username = 'something' 
     password = 'something' 


     server = smtplib.SMTP('smtp.gmail.com:587') 
     server.starttls() 
     server.login(username,password) 
     server.sendmail(fromaddr, toaddrs, msg) 
     server.quit() 

這種方式發送郵件,但郵件的唯一的事情是,我添加到字符串「東西」,並打印輸出味精整個字符串加上「東西」。可能是什麼問題呢?

這是現在整個類,它被稱爲

 mail = Mail() 
    mail.send_mail(message) 
+0

你看到的例外是什麼?我得到'smtplib.SMTPAuthenticationError' – mvanveen 2012-02-07 09:54:05

+0

沒有例外,我在這裏更改了憑據;)這就是爲什麼你得到它。郵件發送,但只有「東西」的郵件,沒有'味精',我傳遞給功能 – iblazevic 2012-02-07 09:56:24

+0

我用我自己的gmail憑據運行它,並得到它......奇怪。如果不能執行它或者看不到其他的類,它是否適合我,你是否試過用其他方式連接,比如'''.join((msg,'something'))'? – mvanveen 2012-02-07 10:02:52

回答

4

我不知道是什麼問題,但我設法使用MIME中已有的蟒蛇

所以這裏將其發送是可以工作的代碼:

def send_mail(self, message): 

    import smtplib 
    from email.MIMEMultipart import MIMEMultipart 
    from email.MIMEText import MIMEText 

    gmailUser = '[email protected]' 
    gmailPassword = 'something' 
    recipient = '[email protected]' 

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

    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() 
+0

你能幫我,如果我必須發送相同的郵件給多個人比我如何做到這一點 – 2013-04-30 07:28:23

0

問題很可能是消息的內容似乎在地址和消息正文之間需要額外的換行符。無論如何,iblazevic提供的解決方案是一種更可讀的方式。