How to fix: ModuleNotFoundError at email.mime [duplicate] - python

This question already has answers here:
ImportError: No module named 'email.mime'; email is not a package [duplicate]
(4 answers)
Closed 3 years ago.
I'm trying to send an email via SMTP also using pythons email module. Since I want to send a file I'm using the MIME module to get this working.
Unfortunately there is some problem importing these email.mime modules which I can not get fixed.
#Imports
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import smtplib
import datetime
mail = 'email#address.net'
#E-Mail Content
msg = MIMEMultipart()
msg['From'] = mail
msg['To'] = mail
msg['Subject'] = 'MesseMahlzeiten Backup Nr.{}'.format('1')
body = datetime.datetime.strftime('%Y-&m-%d %H:%M')
msg.attach(MIMEText(body, 'plain'))
filename = 'WinIcon.jpg'
attachment = open(filenmae, 'rb')
p = MIMEBase('application', 'octet-stream')
p.set_payload(attachment.read())
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename=
{}".format(filename))
msg.attach(p)
content = msg.as_string()
#E-Mail via SMTP
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttsl()
server.login(mail, 'password')
server.sendmail(mail, mail, content)
server.quit()
I'm getting following Error Message:
Traceback (most recent call last):
File "D:/Python/101testprojects/email/email.py", line 2, in <module>
from email.mime.multipart import MIMEMultipart
File "D:\Python\101testprojects\email\email.py", line 2, in <module>
from email.mime.multipart import MIMEMultipart
ModuleNotFoundError: No module named 'email.mime'; 'email' is not a
package
How can I get this import work?

Change the name of the file from email.py to something else. With the original name, Python tries to import from email.py, rather than the email module.
Further reading: ImportError: No module named 'email.mime'; email is not a package

Related

Send video file via mail python

I'm trying to send example.mp4 file with mail in below codes. Mail send successfully. But when I download the video in related mail. Video is not working after download from mail. But normally video is working successfully.Where is my fault ?
import smtplib
from email import message, encoders
from email.message import EmailMessage
from email.mime.base import MIMEBase
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from_addr = 'FROM_MAIL'
to_addr = 'TO_ADDRESS'
subject = 'I just sent this email from Python!'
content = 'Test'
# Initializing video object
video_file = MIMEBase('application', "octet-stream")
# Importing video file
video_file.set_payload(open('example.mp4', "rb").read())
# Encoding video for attaching to the email
encoders.encode_base64(video_file)
# creating EmailMessage object
msg = MIMEMultipart()
# Loading message information ---------------------------------------------
msg['From'] = "person_sending#gmail.com"
msg['To'] = "person_receiving#gmail.com"
msg['Subject'] = 'text for the subject line'
msg.set_content('text that will be in the email body.')
msg.add_attachment(video_file, filename="example.mp4")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(from_addr, 'APP_PASS')
server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
Adding this did it for me:
video_file.add_header('Content-Disposition',
'attachment; filename={}'.format("test.mp4"))

How to solve No module named 'email.MIMEMultipart', when I have tried installing easy_install email?

This is the simple email sending code I have copied from a source and trying to learn it. But this is giving error even after I have installed easy_install email. Below is the code :
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail (from_email, password, to_email, subject, message):
msg=MIMEMultipart()
msg['From']= from_email
msg['To']= to_email
msg['Subject']= subject
msg.attach(MIMEText(message, 'plain'))
try:
server= smtplib.SMTP_SSL('smtp.office365.com', 465)
server.echo()
server.login(from_email, password)
server.sendmail(from_email, to_email, msg.as_string())
server.close()
return True
except Exception as e:
print('Something went wrong '+str())
return False
Traceback (most recent call last):
File "C:\Users\RYadav\PycharmProjects\MAPILab\rough work.py", line 1, in <module>
import smtplib
File "C:\Users\RYadav\PycharmProjects\MAPILab\smtplib.py", line 2, in <module>
from email.MIMEMultipart import MIMEMultipart
ModuleNotFoundError: No module named 'email.MIMEMultipart'
Process finished with exit code 1
use this command :
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
check this lien = https://docs.python.org/3/library/email.mime.html#module-email.mime

Python email PDF: Some PDFs Getting Corrupted

I am trying to attach a PDF file to an e-mail message.
For one PDF (a Word document printed to PDF), it works (the recipient opens it in Outlook with no problem).
Yet for other PDFs (which seem the same except for being a few KBs larger), they get corrupted.
Here is a sample to use which fails (becomes corrupted).
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formatdate
from email import encoders
attachment_path=r'C:\Directory'+'\\'
login='login'
password='password'
part=MIMEBase('application',"octet-stream")
def message(attachment): #attachment is just the PDF file name
fromaddr = "example#example.com"
cc=fromaddr
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = "example#example.com"
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = "Subject"
body='''
<!DOCTYPE html>
<html>
<body>
<p><font face="Tahoma" size=2> I hope everything is going well.</p></font>
</body>
</html>
'''
msg.attach(MIMEText(body, 'html'))
part.set_payload(open(attachment_path+attachment,'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(attachment_path+attachment)))
msg.attach(part)
mail=smtplib.SMTP('Server',587)
mail.ehlo()
mail.starttls()
mail.login(login,password)
mail.sendmail(fromaddr,[toaddr,cc],msg.as_string())
I have tried using the following instead of base 64 encoding, but to no avail:
encoders.encode_noop(part)
encoders.encode_7or8bit(part)
encoders.encode_quopri(part)
Thanks in advance!
All I had to do was move this:
part=MIMEBase('application',"octet-stream")
to just above:
part.set_payload(open(attachment_path+attachment,'rb').read())
I have used below line of code and it is working fine for me.
part=MIMEBase('application/pdf',"octet-stream")

Sending Email attachment (.txt file) using Python 2.7 (smtplib) [duplicate]

This question already has answers here:
How to send email attachments?
(19 answers)
Closed 8 years ago.
So I'm trying to send a .txt file as an attachment and I can't find the right code to work. Here is my code:
import pythoncom
import win32gui
import win32console
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = 'zover1#gmail.com'
toaddrs = 'zover2#gmail.com'
msg = "contrl text file"
username = 'zover1#gmail.com'
password= 'xxxxxxxxxxxx'
server = smtplib.SMTP('smtp.gmail.com:587')
f = file("d:/control.txt")
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="d:/control.txt")
msg.attach(attachment)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
And when I run the module I get this error:
Traceback (most recent call last):
File "C:\Python278\emailonlytester.pyw", line 19, in <module>
msg.attach(attachment)
AttributeError: 'str' object has no attribute 'attach'
Any help would be much appreciated.
You can try this to send an attached file with python:
msg = MIMEMultipart()
msg['From'] = 'your adress'
msg['To'] = 'someone'
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = 'a random subject'
msg.attach(MIMEText("some text"))
file = 'd:/control.txt'
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file,'rb').read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attachment)
This is the part for the creation of the Email, not the sending.
The error is clearly stating the reason. msg is a string in your case. You may want to do the following instead:
msg = MIMEMultipart()
Docs are here.

python email error

I am trying to email a results file. I am getting an import error:
Traceback (most recent call last):
File "email_results.py", line 5, in ?
from email import encoders
ImportError: cannot import name encoders
I am also unsure on how to get this to connect to the server. Can anyone help? Thanks
#!/home/build/test/Python-2.6.4
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
def send_file_zipped(the_file, recipients, sender='myname#myname.com'):
zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
zip = zipfile.ZipFile(zf, 'w')
zip.write(the_file)
zip.close()
zf.seek(0)
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment',filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
The problem isn't that you can't connect to the server, it's that you aren't able to import email.encoders for some reason. Do you have a file named email.py or email.pyc by any chance?

Categories