Smtplib doesn't Work - python

I got the script from the first example here:
https://docs.python.org/2/library/email-examples.html#email-examples
I made sure there is no file name similar to email.py.
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = torontocoinowl#gmail.com
msg['To'] = torontocoinowl#gmail.com
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
The error is
C:\Users\donald\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/donald/PycharmProjects/untitled3/testingemail/ff.py
Traceback (most recent call last):
File "C:/Users/donald/PycharmProjects/untitled3/testingemail/ff.py", line 1, in <module>
import smtplib
File "C:\Users\donald\AppData\Local\Programs\Python\Python35-32\lib\smtplib.py", line 47, in <module>
import email.utils
File "C:\Users\donald\AppData\Local\Programs\Python\Python35-32\lib\email\utils.py", line 28, in <module>
import random
File "C:\Users\donald\PycharmProjects\untitled3\random.py", line 1
From random import randint
^
SyntaxError: invalid syntax
Process finished with exit code 1

You are having a file random.py in your folder. It clashes with the random modul in Python. Remove of rename that file!

Related

I am trying to send an email using python 3.9 using smptlib, why does this not work?

This is my code.
import smtplib
from email.message import EmailMessage
def sendemail(to, subject, message):
msg = EmailMessage()
msg.set_content(message)
msg["subject"] = subject
msg["to"] = to
user = "jibraanahmed234#gmail.com"
msg["from"] = user
password = "pmamhmifmwogjbev"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(user, password)
server.send_message("jibraanahmed234#gmail.com", "jibraanahmed10#gmail.com", msg)
server.quit()
if __name__ == '__main__':
sendemail("jibraanahmed10#gmail.com", "Hello!", "Hi Jibraan!")
This is the error it returns.
Traceback (most recent call last):
File "/Users/jibraanahmed/code/Python/messaging/sendemail.py", line 23, in <module>
sendemail("jibraanahmed10#gmail.com", "Hello!", "Hi Jibraan!")
File "/Users/jibraanahmed/code/Python/messaging/sendemail.py", line 17, in sendemail
server.send_message("jibraanahmed234#gmail.com", "jibraanahmed10#gmail.com", msg)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py",
line 939, in send_message
resent = msg.get_all('Resent-Date')
AttributeError: 'str' object has no attribute 'get_all'
These are all fake passwords and emails.
I have tried a lot of tutorials that look like they work for most people, what am I doing wrong?
Maybe you should try sendmail instead of send_message.
From the docs:
The arguments have the same meaning as for sendmail(), except that msg is a Message object

Unable to send mail using python with multiple attachment and multiple recipients [to,cc,bcc]

Below is my code. It is unable to send mail somewhere at parsing level. Not able to understand the actual issue. OS is Ubuntu 14.04 Server provided by AWS. It has to send email with two attachments.
import smtplib
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "user#comany.com"
toaddr = str(sys.argv[1]).split(",")
ccaddr = str(sys.argv[2]).split(",")
bccaddr = str(sys.argv[3]).split(",")
subject = None
body = None
print sys.argv
with open("subject.txt") as f1:
subject = f1.read()
with open("body.txt") as f2:
body = f2.read()
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Cc'] = ccaddr
msg['Bcc'] = bccaddr
msg['Subject'] = subject.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
body = body.replace("DD",str(sys.argv[4])[6:2]).replace("MM",str(sys.argv[4])[4:2]).replace("YYYY",str(sys.argv[4])[0:4])
msg.attach(MIMEText(body, 'plain'))
for filename in str(sys.argv[5]).split(";"):
attachment = open(filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(fromaddr, "password")
server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
Here is the error:
File "send_mail.py", line 49, in <module>
server.sendmail(fromaddr, toaddr, msg.as_string())
File "/usr/lib/python2.7/email/message.py", line 137, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python2.7/email/generator.py", line 83, in flatten
self._write(msg)
File "/usr/lib/python2.7/email/generator.py", line 115, in _write
self._write_headers(msg)
File "/usr/lib/python2.7/email/generator.py", line 164, in _write_headers
v, maxlinelen=self._maxheaderlen, header_name=h).encode()
File "/usr/lib/python2.7/email/header.py", line 410, in encode
value = self._encode_chunks(newchunks, maxlinelen)
File "/usr/lib/python2.7/email/header.py", line 370, in _encode_chunks
_max_append(chunks, s, maxlinelen, extra)
File "/usr/lib/python2.7/email/quoprimime.py", line 97, in _max_append
L.append(s.lstrip())
AttributeError: 'list' object has no attribute 'lstrip'
Try it with yagmail. Disclaimer: I'm the developer of yagmail.
import yagmail
yag = yagmail.SMTP("user#comany.com", "password")
yag.send(toaddrs, subject, body, str(sys.argv[5]).split(";"), ccaddrs, bccaddrs)
# ^ to ^subject ^ body ^ attachments ^ cc ^ bcc
It's pretty much "Do What I Want", you can provide lists of strings or a single string, even omit any arguments, and it will be sensible. Another cool thing is that the attachments here is a list of strings; where each will be tried to be loaded as file (with correct mimetype).
Use pip install yagmail to install
I had the same problem when I tried to feed a list in to msg['To']. I changed the list to string and I got rid of the problem. ['test#my.com', 'another#my.com'] => 'test#my.com, another#my.com'

ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590)

I am sending a few scheduled emails via gmail, with python 2.7 on windows. A couple of days ago, I started getting this error, without having made any changes to the job, the python install or the windows server.
It is the first email of the day being sent. Subsequent emails go through just fine. When running manually it from command line in the morning, it runs just fine.
Any ideas of what could be wrong, or how to fix/workaround it are appreciated.
My method from 'mymethodsfile' look like this
import sys
import ast
from datetime import datetime
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
def send(self):
msg = MIMEMultipart('alternative')
msg['From']=self.sender
msg['Subject']=self.subject
msg['To'] = ", ".join(self.recipients) # to must be array of the form ['mailsender135#gmail.com']
#msg.preamble = "preamble goes here"
#check if there are attachments if yes, add them
if self.attachments:
self.attach(msg)
#add html body after attachments
msg.attach(MIMEText(self.htmlbody, 'html'))
#send
s = smtplib.SMTP('smtp.gmail.com:587')
s.starttls()
s.login(self.sender,self.senderpass)
s.sendmail(self.sender, self.recipients, msg.as_string())
s.quit()
Error in the logs(script path and filename anonymised):
Traceback (most recent call last):
File "C:\path\filename.py", line 12, in <module>
mymail.send()
File "C:\path2\mymethodsfile.py", line 49, in send
s.starttls()
File "C:\Python27\lib\smtplib.py", line 649, in starttls
self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
File "C:\Python27\lib\ssl.py", line 911, in wrap_socket
ciphers=ciphers)
File "C:\Python27\lib\ssl.py", line 579, in __init__
self.do_handshake()
File "C:\Python27\lib\ssl.py", line 808, in do_handshake
self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590)
stoping using system proxy while running the code may be helpful.

Python SMTP error: "(10013, 'Permission denied')"

So I have this Python send-email file that sends an email (the text from a file) to a recipient specified inside the code:
import smtplib
from email.mime.text import MIMEText
msgContent = open(Sourcefilelocation, "rb")
msg = MIMEText(spam.read())
msgContent.close()
msg['Subject'] = SUBJECT
msg['From'] = FROM_CLIENT_EMAIL
msg['To'] = TO_CLIENT_EMAIL
#THE ERROR BELOW
s = smtplib.SMTP('localhost')
I understand that there is no mail server on localhost, but how do I make a mail server on that and if I can't then why does s = smtplib.SMTP('gmail.com') take so long if it even works? What do I need to make it work? Any help is appreciated.
output: >> Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s = smtplib.SMTP('gmail.com')
File "C:\Python25\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python25\lib\smtplib.py", line 310, in connect
raise socket.error, msg
error: (10013, 'Permission denied')
And the gmail smtp code takes too long.

python html mail failure

I'm struggling to figure out what went wrong with the below code.
I'm trying to send html mail.
NOW = datetime.datetime.now()
def sendEmail(msg):
global NOW
global SENDER
global EMAILTARGET
today = "%s/%s/%s" % (NOW.month,NOW.day,NOW.year)
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "SAR Data Report - %s" % today
msg['From'] = SENDER
msg['To'] = EMAILTARGET
chunk = MIMEText(msg, 'html')
msg.attach(chunk)
s = smtplib.SMTP('localhost')
s.sendmail(SENDER, EMAILTARGET, msg.as_string())
s.quit()
the above code gives me the following error:
Traceback (most recent call last):
File "./html_mail.py", line 295, in <module>
sendEmail(html)
File "./html_mail.py", line 245, in sendEmail
chunk = MIMEText(msg, 'html')
File "/usr/lib/python2.7/email/mime/text.py", line 30, in __init__
self.set_payload(_text, _charset)
File "/usr/lib/python2.7/email/message.py", line 226, in set_payload
self.set_charset(charset)
File "/usr/lib/python2.7/email/message.py", line 268, in set_charset
cte(self)
File "/usr/lib/python2.7/email/encoders.py", line 73, in encode_7or8bit
orig.encode('ascii')
AttributeError: MIMEMultipart instance has no attribute 'encode'
The error in your code is that you've used msg as an in-parameter to your function and it collides with your MIME message container (both named msg).
What you need to do is to change the name of the in-parameter to something else, like html:
def sendEmail(html):
...
chunk = MIMEText(html, 'html')
...
You're passing msg, which is a MIMEMultipart object, to the MIMEText initializer, which expects a string. You should be passing a string containing the HTML you want to attach, not the message you're trying to attach it to.

Categories

Resources