问题
My code is running and sending the mail. But To and Subject are not coming in the mail. Here is a snippet of the code i used. What could be the issue?
Code :
username = "N@EXAMPLE.com"
password = "fnEOFINO”
print("Logged in")
sender = 'n@example.com'
receivers = 'T@example.com'
message = """From: Neeraja Rajiv <NRajiv@EXAMPLE.com>
To: T@EXAMPLE.COM
Subject: SMTP e-mail test
Overall
%d
"""%(variable)
print("Connecting to server")
server = smtplib.SMTP('SMTP-********.com', 25)
print("Connected to server")
server.set_debuglevel (1)
server.sendmail(sender,receivers,message)
print ("Successfully sent email")
In the Email, subject is missing.
Any approaches/suggestions are most welcome.
回答1:
I think your problem lies in how you have created your message, the corrected version works using it with the example code below:
msg = """From: 'From Neeraja Rajiv <NRajiv@EXAMPLE.com>'
To: 'To Toffet Joseph - Consultant <TJoseph@EXAMPLE.com>'
Subject: 'SMTP e-mail test'
Overall'{}'""".format(variable)
username = "foo"
password = "bar"
print("Logged in")
import smtplib
sender = "foo@gmail.com"
receivers = "bar@gmail.com"
msg = """From: 'From Neeraja Rajiv <NRajiv@EXAMPLE.com>'
To: 'To Toffet Joseph - Consultant <TJoseph@EXAMPLE.com>'
Subject: 'SMTP e-mail test'"""
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(sender, receivers , msg)
server.quit()
回答2:
Padraic Cunningham example looks correct. Here is another example. Maybe this might help...
Sample Email To SMTP Server Python Script:
import smtplib
try:
host = '?.?.?.?' #The Address To Your SMTP Server...
port = 25
to = 'reciever@someplace.com' #Reciever Of Email...
from_addr = 'sender@someplace.com' #Sender Of Email...
subject = '<YOUR SUBJECT HERE>' #Subject Of Email...
text_line_1 = 'Body Line 1...\r\n' #Body Of Email...
text_line_2 = '\r\n'
text_line_3 = 'Body Line 3...\r\n'
text_line_4 = '\r\n'
text_line_5 = 'Body Line 5...\r\n'
total_message = text_line_1 + text_line_2 + text_line_3 + text_line_4 + text_line_5
msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (from_addr, [to], subject, total_message)
server = smtplib.SMTP(host, port)
server.sendmail(from_addr, to, msg)
print('Successfully Sent Email...')
except Exception as e: print('Exception: ' + str(e))
Good Luck...
来源:https://stackoverflow.com/questions/25056789/subject-line-not-coming-in-the-smtp-mail-sent-from-python