2017-09-08 59 views
0

這裏是我的代碼如何在Python電子郵件的腳本發件人地址前添加發件人名稱

 
    # Import smtplib to provide email functions 
    import smtplib 

    # Import the email modules 
    from email.mime.multipart import MIMEMultipart 
    from email.mime.text import MIMEText 

    # Define email addresses to use 
    addr_to = '[email protected]' 
    addr_from = '[email protected]' 

    # Define SMTP email server details 
    smtp_server = 'smtp.aol.com' 
    smtp_user = '[email protected]' 
    smtp_pass = 'pass' 

    # Construct email 
    msg = MIMEMultipart('alternative') 
    msg['To'] = addr_to 
    msg['From'] = addr_from 
    msg['Subject'] = 'test test test!' 

    # Create the body of the message (a plain-text and an HTML version). 
    text = "This is a test message.\nText and html." 
    html = """\ 

    """ 

    # Record the MIME types of both parts - text/plain and text/html. 
    part1 = MIMEText(text, 'plain') 
    part2 = MIMEText(html, 'html') 

    # Attach parts into message container. 
    # According to RFC 2046, the last part of a multipart message, in this case 
    # the HTML message, is best and preferred. 
    msg.attach(part1) 
    msg.attach(part2) 

    # Send the message via an SMTP server 
    s = smtplib.SMTP(smtp_server) 
    s.login(smtp_user,smtp_pass) 
    s.sendmail(addr_from, addr_to, msg.as_string()) 
    s.quit() 

我只是想收到的電子郵件顯示之前像這樣的發件人的電子郵件地址發送者姓名:sender_name

回答

0

這取決於關於「友好名稱」是基本ASCII還是需要特殊字符。

基本例如:

msg['From'] = str(Header('Magnus Eisengrim <[email protected]>')) 

如果您需要使用非US-ASCII字符,它更復雜,但附加的文章應該幫助,這是非常透徹:http://blog.magiksys.net/generate-and-send-mail-with-python-tutorial

+0

這將改變接收機名稱!! – mrassili

+0

更新了答案,但是同樣的邏輯適用於「From」標題以及「To」標題。 – meisen99

相關問題