Specify a sender when sending mail with Python (smtplib)

前端 未结 6 1235
不思量自难忘°
不思量自难忘° 2020-12-02 00:19

I have a very simple piece of code (just for testing):

import smtplib
import time

server = \'smtp.myprovider.com\'
recipients = [\'johndoe@somedomain.com\']         


        
6条回答
  •  旧巷少年郎
    2020-12-02 00:46

    See this answer, it's working for me.

    example code:

    #send html email
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import formataddr
    
    msg = MIMEMultipart('alternative')
    msg['From'] = formataddr((str(Header('MyWebsite', 'utf-8')), 'from@mywebsite.com'))
    msg['To'] = 'to@email.com'
    
    html = "email contents"
    
    # Record the MIME types of text/html.
    msg.attach(MIMEText(html, 'html'))
    
    # Send the message via local SMTP server.
    s = smtplib.SMTP('localhost')
    
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    s.sendmail('from@mywebsite.com', 'to@email.com', msg.as_string())
    s.quit()
    

提交回复
热议问题