简体   繁体   中英

convert string arguments to send e-mail can help me please (python)

import smtplib
import sys
if(len(sys.argv) > 1):
 smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
 smtp.login('gmail.com', 'password')
 de = '@gmail.com'
 para = ['@gmail.com']
 msg2=str(sys.argv[1])
 msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+"""""" % (de, ', '.join(para))

i have this error: TypeError: not all arguments converted during string formatting in msg2

 smtp.sendmail(de, para, msg)
 smtp.close()
 print "sending message"

This is the part thats actually breaking

msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+"""""" % (de, ', '.join(para))

If we break this up what you are telling python to do is:

"""first string %s %s """ +\    # a string of text with 2 placeholders
 msg2 +\                        # a string
 """""" % (de, ', '.join(para)) # empty string of text with no placeholders
                                # (formatted with 2 variables)

what you actually want is probably something like this:

msg = """From: %s
To: %s
Subject: SMATIJ
server""" % (de, ', '.join(para)) + msg2 

I believe the issue is that Python is trying to group your strings like -

msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+("""""" % (de, ', '.join(para)))

Hence, it trying to apply the strings to the empty strings at the end (not even sure why you need the empty string) , which is causing the issue. You should group the string concatenation together manually. Example -

msg = ("""From: %s
To: %s
Subject: SMATIJ
server"""+msg2) % (de, ', '.join(para))

Or better yet, use the more powerful str.format , Example -

msg = """From: {0}
To: {1}
Subject: SMATIJ
server{2}""".format(de, ', '.join(para), msg2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM