mail is delivering without subject when calling from function in python - python

I have a sample code like following:
import smtplib
def send_mail(PASS,FAIL):
me = "XXXX"
you = "YYYY"
print "Start of program"
server = smtplib.SMTP('ZZZ', 25)
total_testcase = "15/12"
print total_testcase
message = """From: From Person <XXXX>
To: To Person <YYYY>
Subject: mail testing
%s
""" %total_testcase
print message
server.sendmail(me, you, message)
send_mail(8,9)
when I am sending the email it is delivering without the subject
But if I use the code instead of a function call - then it is delivering fine with subject. Anything I am missing in a function call. Please suggest.

The issue you're having is with the triple-quoted multi-line string. When you put it in your function, you're indenting all of its lines so that they line up with the rest of the code. However, this results in unnecessary (and inappropriate) spaces at the start of each line of the message after the first.
Leading spaces in the headers of an SMTP message indicate that the previous header should be continued. This means that all of your first three lines are combined into the From header.
You can fix this either by leaving out the leading spaces:
def send_mail(PASS,FAIL):
#...
message = """From: From Person <XXXX>
To: To Person <YYYY>
Subject: mail testing
%s
""" % total_testcase
#...
Or by using \n instead of real newlines in your string:
message = "From: From Person <XXXX>\nTo: To Person <YYYY>\nSubject: mail testing\n\n%s" % total_testcase
Or finally, you could keep the current code for the generation of the message, but strip out the leading whitespace afterwards:
def send_mail(PASS,FAIL):
#...
message = """From: From Person <XXXX>
To: To Person <YYYY>
Subject: mail testing
%s
""" % total_testcase
message = "\n".join(line if not line.startswith(" ") else line[4:]
for line in message.splitlines())
#...
This last option is a bit fragile, as it may strip out desired whitespace from lines in your total_testcase string (if it had multiple lines), not only the spaces added due to the multi-line string. It also will break if you're using tabs for indentation, or really anything other than four spaces. I'm not sure I'd actually recommend this approach.
A better version of the last approach is to use the textwrap.dedent function from the the standard library. It removes any indentation that is present at the start of every line in a string (but only the indentation that is common to all lines). This does require a small change to how you were creating message, as you need the first line to have the same leading spaces as all the rest (you'll also need to avoid adding any newlines without indentation in the extra text that comes from total_testcase).
Here's the code:
import textwrap
def send_mail(PASS,FAIL):
#...
# backslash after the quotes on the first line avoids a empty line at the start
message = """\
From: From Person <XXXX>
To: To Person <YYYY>
Subject: mail testing
%s
""" % total_testcase
message = textwrap.dedent(message)
#...

Related

Gmail API Python Plain Text is Not Wrapping in Body of Email

When I send an email the plain text is not wrapping. I read that you can't have more than 80 characters in a line or Gmail automatically makes a break and it makes the text look horrible on a phone. I put 'html' as second parameter in MIMETEXT(). This wraps the text, but does not include any Python escape characters. I can't figure out how to make line breaks?
Code:
I set MIMEText with 'html' parameter and this seems to wrap text, but in a block with out any of the Python escape characters being used.
def CreateMessageHtml(sender, to, subject, message_text):
msg = MIMEText(message_text,'html')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = to
return {'raw': base64.urlsafe_b64encode(msg.as_string())}
Issue is in the message_text, not sure how to create a line break because \n is not working.
def main():
df = pd.read_csv('testdata.csv')
for index,row in df.iterrows():
to = row['Email']
sender = "sender"
subject = "subject"
dedent_text = '''Hello {}, \n
Thank you for attending our last meeting. We would
like to see you again at our next event.'''.format(row['First'])
message_text = textwrap.dedent(dedent_text).strip()
SendMessage(sender, to, subject, message_text)
if __name__ == '__main__':
main()
In the function CreateMessageHtml the MIMEText object takes a subtype, which is 'HTML'. From the documentation: https://docs.python.org/2/library/email.mime.html#email.mime.text.MIMEText
class email.mime.text.MIMEText(_text[, _subtype[, _charset]])
Module: email.mime.text
A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain.
Based on this you need to pass in a HTML formatted string. So I changed the dedent_text in the main function to:
dedent_text='''Hello {},
<p> Thank you for attending our last meeting.</P>
<p>We would like to see you again at our next
event.</p>'''.format(row['First'])
Now the text wraps on a phone with line breaks.
Try using triple quotes """ TEXT """ instead of triple apostrophes. Tried this:
mytext = """I'm going \n down down \n down """
print mytext
and the output was:
I'm going
down down
down

Python, adding comma in smtplib argument causes error

While sending an email with smtplib and trying to insert a variable into the message with this code:
smtpObj.sendmail('my email', 'my email', "Subject: Info for today. \nToday's weather is:",con)
(where con is weather scraped from the internet)
throws the following error:
File "C:\Python27\lib\smtplib.py", line 731, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (501, '5.5.4 Invalid arguments', 'my email here')
However, when I simply use "+" to concatenate the two strings, rather than a comma, it works, but does not format properly, displaying as "..weather is:rain" rather than "..weather is: rain"
am I doing something wrong, or is this simply not possible?
However, when I simply use "+" to concatenate the two strings, rather than a comma, it works, but does not format properly, displaying as "..weather is:rain" rather than "..weather is: rain"
You are simply mis-constructing the string that begins with "Subject" here:
smtpObj.sendmail('my email', 'my email', "Subject: Info for today. \nToday's weather is:",con)
When you tack on con with a comma like you are doing here, Python thinks that you are passing conn as the mail_options argument of the sendmail() call, the same as your other arguments to that function. It does not understand that you are trying to cram con into that "Subject: ..." string.
However, when I simply use "+" to concatenate the two strings, rather than a comma, it works, but does not format properly, displaying as "..weather is:rain" rather than "..weather is: rain"
So you just need an extra space after the "..weather is:" bit? Just add the extra space in the string. I suggest you write your message with the con argument in one of these ways:
msg = "Subject: Info for today. \nToday's weather is: " + con
# or like this:
msg = "Subject: Info for today. \nToday's weather is: %s" % (con,)
And then send your email:
smtpObj.sendmail('my email', 'my email', msg)

Python mail inserts space every 171 characters

I am trying to write a python script to send an email that uses html formatting and involves a lot of non-breaking spaces. However, when I run it, some of the &nbsp strings are interrupted by spaces that occur every 171 characters, as can be seen by this example:
#!/usr/bin/env python
import smtplib
import socket
from email.mime.text import MIMEText
emails = ["my#email.com"]
sender = "test#{0}".format(socket.gethostname())
message = "<html><head></head><body>"
for i in range(20):
message += " " * 50
message += "<br/>"
message += "</body>"
message = MIMEText(message, "html")
message["Subject"] = "Test"
message["From"] = sender
message["To"] = ", ".join(emails)
mailer = smtplib.SMTP("localhost")
mailer.sendmail(sender, emails, message.as_string())
mailer.quit()
The example should produce a blank email that consists of only spaces, but it ends up looking something like this:
&nbsp ;
&nb sp;
& nbsp;
&nbs p;
&n bsp;
Edit: In case it is important, I am running Ubuntu 15.04 with Postfix for the smtp client, and using python2.6.
I can replicate this in a way but my line breaks come every 999 characters. RFC 821 says maximum length of a line is 1000 characters including the line break so that's probably why.
This post gives a different way to send a html email in python, and i believe the mime type "multipart/alternative" is the correct way.
Sending HTML email using Python
I'm the developer of yagmail, a package that tries to make it easy to send emails.
You can use the following code:
import yagmail
yag = yagmail.SMTP('me#gmail.com', 'mypassword')
for i in range(20):
message += " " * 50
message += "<br/>"
yag.send(contents = message)
Note that by default it will send a HTML message, and that it also adds automatically the alternative part for non HTML browsers.
Also, note that omitting the subject will leave an empty subject, and without a to argument it will send it to self.
Furthermore, note that if you set yagmail up correctly, you can just login using yag.SMTP(), without having to have username & password in the script (while still being secure). Omitting the password will prompt a getpass.
Adding an attachment is as simple as pointing to a local file, e.g.:
yag.send(contents = [message, 'previously a lot of whitespace', '/local/path/file.zip']
Awesome isn't it? Thanks for the allowing me to show a nice use case for yagmail :)
If you have any feature requests, issues or ideas please let me know at github.

python-xmpp and looping through list of recipients to receive and IM message

I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way.
Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, in XMPP/Jabber ID format. This is read into a Python list variable.
I then instantiate an XMPP client session and loop through the list of recipients and send a message to each recipient. Then sleep some time and repeat test. This is for load testing the IM client of recipients as well as IM server. There is code to alternately handle case of taking only one recipient from command line input instead of from file.
What ends up happening is that Python does iterate/loop through the list but only last recipient in list receives message. Switch order of recipients to verify. Kind of looks like Python XMPP library is not sending it out right, or I'm missing a step with the library calls, because the debug print statements during runtime indicate the looping works correctly.
recipient = ""
delay = 60
useFile = False
recList = []
...
elif (sys.argv[i] == '-t'):
recipient = sys.argv[i+1]
useFile = False
elif (sys.argv[i] == '-tf'):
fil = open(sys.argv[i+1], 'r')
recList = fil.readlines()
fil.close()
useFile = True
...
# disable debug msgs
cnx = xmpp.Client(svr,debug=[])
cnx.connect(server=(svr,5223))
cnx.auth(user,pwd,'imbot')
cnx.sendInitPresence()
while (True):
if useFile:
for listUser in recList:
cnx.send(xmpp.Message(listUser,msg+str(msgCounter)))
print "sending to "+listUser+" msg = "+msg+str(msgCounter)
else:
cnx.send(xmpp.Message(recipient,msg+str(msgCounter)))
msgCounter += 1
time.sleep(delay)
Never mind, found the problem. One has to watch out for the newline characters at the end of a line for the elements in a list returned by file.readlines(), so I had to strip it out with .rstrip('\n') on the element when sending out message.

Python: email get_payload decode fails when hitting equal sign?

Running into strangeness with get_payload: it seems to crap out when it sees an equal sign in the message it's decoding. Here's code that displays the error:
import email
data = file('testmessage.txt').read()
msg = email.message_from_string( data )
payload = msg.get_payload(decode=True)
print payload
And here's a sample message: test message.
The message is printed only until the first "=" . The rest is omitted. Anybody know what's going on?
The same script with "decode=False" returns the full message, so it appears the decode is unhappy with the equal sign.
This is under Python 2.5 .
You have a line endings problem. The body of your test message uses bare carriage returns (\r) without newlines (\n). If you fix up the line endings before parsing the email, it all works:
import email, re
data = file('testmessage.txt').read()
data = re.sub(r'\r(?!\n)', '\r\n', data) # Bare \r becomes \r\n
msg = email.message_from_string( data )
payload = msg.get_payload(decode=True)
print payload

Categories

Resources