python email error - python

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?

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

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

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

Adding email attachments using smtplib

I'm trying to send emails and attach a VCF file, but I'm running into some trouble. I've managed to send emails with plain text without any issues, but here's the error I'm getting when I run my code now:
AttributeError: 'file' object has no attribute 'rfind'
And my code:
import vobject
import requests
import smtplib
from os.path import basename
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
j = vobject.vCard()
j.add('n')
j.n.value = vobject.vcard.Name(family='Harris', given='Jeffrey')
j.add('fn')
j.fn.value = 'Jeffrey Harris'
j.add('email')
j.email.value = 'jeffrey#osafoundation.org'
j.email.type_param = 'Internet'
k = j.serialize()
with open ('new.vcf', 'w') as file:
file.write(k)
with open('new.vcf', 'rb') as fil:
part = MIMEApplication(
fil.read(),
Name=basename(fil)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(fil)
msg = MIMEMultipart()
msg['From'] = 'me#myemail.com'
msg['To'] = 'me#myemail.com'
msg['Subject'] = 'test'
message = 'test'
msg.attach(part)
mailserver = smtplib.SMTP('secure.emailsrvr.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login('me#myemail.com', 'mypassword')
mailserver.sendmail('me#myemail.com','me#myemail.com',msg.as_string())
mailserver.quit()
Any ideas on what I'm doing wrong?
Your problem is in Name=basename(fil) because basename() accept str, bytes or os.PathLike object.
You are trying to pass _io.BudderReader as an argument.
Solution:
You should pass the filename of the attachment (in OP case is new.vcf).

python can't send attachment files through email

I have the following code which works fine, but it doesn't send the attachment files.
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
msg=MIMEMultipart()
def mymail(address,body,format,mylist=None):
msg['To']=address
msg['From']='ggous1#gmail.com'
if format=='txt':
text_msg=MIMEText(body,'plain')
elif format=='html':
text_msg=MIMEText(body,'html')
msg.attach(text_msg)
if mylist is not None:
mylist=[]
fn=[]
for f in range(len(mylist)):
direct=os.getcwd()
os.chdir(direct)
part=MIMEBase('application','octet-stream')
part.set_payload(open(mylist[f],'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(mylist[f]))
fn.append(part)
msg.attach(fn)
srv=smtplib.SMTP('smtp.gmail.com')
srv.set_debuglevel(1)
srv.ehlo()
srv.starttls()
srv.ehlo()
srv.login('username','pass')
srv.sendmail(msg['From'],msg['To'],msg.as_string())
srv.quit()
if __name__=="__main__":
address=raw_input('Enter an address to send email in the form "name#host.com" ')
body=raw_input('Enter the contents of the email')
format=raw_input('The format is txt or html?')
question=raw_input('Do you have any files to attach?Yes or No?')
mylist=[]
if question=='Yes' or question=='yes':
fn=raw_input('Enter filename')
mylist.append(fn)
mymail(address,body,format,mylist)
Am I not using MIMEBase right, or do I have an error in my code?
UPDATE------------------------
if mylist is not None:
mylist=[]
fn=[]
for f in range(len(mylist)):
direct=os.getcwd()
os.chdir(direct)
fn[f]=open(mylist[f],'r')
part=msg.attach(MIMEApplication(fn[f]))
mylist.append(part)
I would recommend to use MIMEApplication instead for the attachment. You also do not need to do all the payload encoding manually since that is already done automatically. This example works for me:
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formataddr
from email.utils import make_msgid
from email.utils import formatdate
email = MIMEMultipart()
email['From'] = formataddr(('Jane Doe', 'jane#example.com'))
email['Subject'] = u'Test email'
email['Message-Id'] = make_msgid()
email['Date'] = formatdate(localtime=True)
email.attach(MIMEText(u'This is your email contents.'))
email.attach(MIMEApplication('your binary data'))
print email.as_string()
Note that I'm also taking care to set a proper Date and Message-Id header here.
Applying that to your code (and doing a few small cleanups) I get the following working code:
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import make_msgid
from email.utils import formatdate
def make_mail(address,body,format,mylist=[]):
msg = MIMEMultipart()
msg['To'] = address
msg['From'] = 'ggous1#gmail.com'
msg['Message-Id'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(body, 'plain' if format == 'txt' else 'html'))
for filename in mylist:
part = MIMEApplication(open(filename).read())
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(filename))
msg.attach(part)
return msg
def send_mail(msg):
srv = smtplib.SMTP('smtp.gmail.com')
srv.set_debuglevel(1)
srv.ehlo()
srv.starttls()
srv.ehlo()
srv.login('username','pass')
srv.sendmail(msg['From'], msg['To'], msg.as_string())
srv.quit()
if __name__=="__main__":
address=raw_input('Enter an address to send email in the form "name#host.com" ')
body=raw_input('Enter the contents of the email')
format=raw_input('The format is txt or html?')
question=raw_input('Do you have any files to attach?Yes or No?')
mylist=[]
if question=='Yes' or question=='yes':
fn=raw_input('Enter filename')
mylist.append(fn)
msg = make_mail(address,body,format,mylist)
send_mail(msg)

Categories