I have basic script that can send properly emails:
#!/usr/bin/python
import smtplib
sender = 'demo@mail.com'
receivers = ['demo2@mail.com']
message = """From:Email cronjob <demo@mail.com> Subject:
Anything
Some more text """
message = message + "\nso far so good"
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers,message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
With snippet above the email is properly sent, however if I put the same script as a method that looks like this:
#!/usr/bin/python
import smtplib
def sendMail(text):
sender = 'demo@mail.com'
receivers = ['demo2@mail.com']
message = """From: Email cronjob <demo@mail.com>
Subject: Anything
Initial text """
message = message + text
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
sendMail("\nlet's try it")
The email is sent but the sender address, the email title and the recipient address are not longer visible in the r开发者_运维知识库eceived email, just the body text.
How can I fix this?
Indent your code properly and make sure the the email headers like From and Subject are in their own line separated by atleast a newline (\n) character and then there is the body of the email. You should have a consistent behavior in both your examples.
This worked out:
message = """From: %s\nTo: %s\nSubject: My subject\a title\n\n%s""" % (sender, receivers, results).
Thanks.
精彩评论