How do I print the text from function in email message? - python

Fairly new to python and currently exploring ways automate emails from functions.
Everytime I send this message the text just says 'None' in my inbox.
def attendance_1(*students):
#Would like this message to appear in body of text
print(f"Hello, could you please send out an attendance text to the following student(s)
please:\n")
for student in students:
print(f"- {student}")
print("\nThank you very much")
#Info of students
example_1 = "example_1#gmail.com"
example_2 ="example_2#gmail.com"
#Send Message
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
subject = 'Attendance warning 1'
body = (attendance_1(example_1, example_2))
msg = f'Subject: {subject}\n\n{body}'
smtp.sendmail(SENDER, RECEIVER, msg)

def attendance_1(students):
s = f"Hello, could you please send out an attendance text to the following student(s) please:\n"
for student in students:
s += f"- {student}"
s += "\nThank you very much"
return s
#Info of students
students = ["example_1#gmail.com", "example_2#gmail.com"]
#Send Message
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
subject = 'Attendance warning 1'
body = attendance_1(students)
msg = f'Subject: {subject}\n\n{body}'
smtp.sendmail(SENDER, RECEIVER, msg)
I didn't test this code so there could be some errors.

Related

Send Reply to email thread

I'm trying to reply to an email based on the following criteria:
Scan the inbox for unseen mails with specific Subject content, if there is mails that satisfy those criteria then: send back an reply message to the sender saying "something", if those criteria are not met then: send back an reply message to the sender saying "something".
This is what i came up with so far:
import imaplib
import email
import smtplib
username = 'sample#gmail.com'
password = 'xxxx'
imap_server = imaplib.IMAP4_SSL('smtp.gmail.com')
imap_server.login(username, password)
imap_server.select('INBOX')
result, data = imap_server.search(None, '(UNSEEN)')
email_ids = data[0].split()
for email_id in email_ids:
result, data = imap_server.fetch(email_id, "(RFC822)")
raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)
subject = email_message["Subject"]
if subject == "SOME SPECIFIC CONTENT":
reply = email.message.EmailMessage()
reply["To"] = email_message["From"]
reply["Subject"] = "Re: " + email_message["Subject"]
reply["In_Reply-To"] = email_message["From"]
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(username, reply["In_Reply-To"], 'Subject: Criteria met\n\nThank you.')
server.quit()
else:
reply = email.message.EmailMessage()
reply['To'] = email_message['From']
reply['Subject'] = "RE:" + email_message['Subject']
reply["In_Reply-To"] = email_message["From"]
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(username, reply["In_Reply-To"], 'Subject: Criteria not met\n\Thank you.')
print('Sending email')
server.quit()
imap_server.close()
It sends the email but without the desired thread, just sends a new email and not actually replying back to the sender.
Any suggestion on how to modify the code so it actually send an reply with the desired thread?
Thank you in advance.
Like the comment mentions, you should use the Message-Id of the original message, not the sender address.
Also, you should obey Reply-To: and add References:.
reply = email.message.EmailMessage()
reply["To"] = email_message["Reply-To"] or email_message["From"]
reply["Subject"] = "Re: " + email_message["Subject"]
reply["In_Reply-To"] = email_message["Message-Id"]
reply["References"] = (email_message["References"] or "") + " " + email_message["Message-Id"]
Properly speaking, the References: header should be trimmed from the middle if it's too long.
Some vendors have their own nonstandard threading extensions; in particular, Microsoft's Thread-Id: etc headers are probably best ignored.

Use Python to send SMS as a given name

How can I send an SMS email as a name such as Joe Doe or (846) 596-2256?
I can send an SMS message to a phone number with any email I want with this code here
import smtplib
to = 'xxxxxxxxxx#xxxx.com'
sender_user = 'xxx#provider.com'
sender_pwd = 'xxx'
fake_email = 'fake#fake.com'
fake_name = 'Fake Name'
message = 'This is a test message!'
smtpserver = smtplib.SMTP("smtp.emailprovider.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(sender_user, sender_pwd)
header = f'To: {to}\nFrom: "{fake_name}" <{fake_email}>\nSubject: \n'
msg = header + '\n' + message + '\n\n'
smtpserver.sendmail(sender_user, to, msg)
smtpserver.close()
And it appears on the phone like this
Is it possible to remove the #domain.com part? If I do not enter a valid email (Containing a *#*.*) the text message will either not go through entirely or appear as a text message sent by 6245 which after a bit of research is the number which Verizon (my carrier) will send an invalid SMS as. Can I do this with just a python script?

Python Email Notification Not Sending

This code is supposed to send an email to a specified address and when I hard code the "TEXT" & "SUBJECT" it seems to send fine but when I create it as a function and call it it never sends the email and never prints the "Notification Sent" message. What am I missing?
Tried hard coding the TEXT and SUBJECT and it sends fine! NOTE: YOU MUST ENABLE LESS SECURE APPS WHEN USING GMAIL!
import smtplib
class email_thing:
def email_notification(self,SUBJECT,TEXT):
TO = 'email#example.com'
self.SUBJECT = SUBJECT
self.TEXT = TEXT
gmail_sender = 'email#example.com'
gmail_passwd = 'examplepassword'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
return self.SUBJECT
return self.TEXT
BODY = '\r\n'.join(['To: %s' % TO,
'From: %s' % gmail_sender,
'Subject: %s' % SUBJECT,
'',TEXT])
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('Notification Sent!')
except:
print ('error sending mail')
server.quit()
test_send = email_thing()
test_send.email_notification(SUBJECT ='Test Email',TEXT = 'This is a test from python!')
Remove
return self.SUBJECT
return self.TEXT
return exits method at once so code after return is never executed.

Python poplib: retrieving body of the email result to NONE

I can get the subject of the email however the body always result to NONE. Tried following this link but all the suggestions end up the same. The body still prints as NONE.
import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('my_email.com')
pop_conn.pass_('my_password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ['\n'.join(map(bytes.decode, mssg[1])) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print (message['subject'])
print (message['body'])
print (message.get_payload())
pop_conn.quit()
import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('my_email.com')
pop_conn.pass_('my_password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ['\n'.join(map(bytes.decode, mssg[1])) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print (message['subject'])
print (message['from'])
for part in message.walk():
if part.get_content_type():
body = part.get_payload(decode=True)
print(body)
pop_conn.quit()
This did the trick. However it prints a straight line. Anybody know how to print per line if the body of the message is long?

Python SMTP what is wrong with the syntax?

I am very new to this whole Python 3.4 syntax and need some help working out this portion of my SMTP mailer. Anyways, if you could help that would be great! Below is the code in Python script.
print ('SMTP Mailbox Spammer v1')
import smtplib
smtpObj = smptlib.SMTP( [smtp.gmail.com [ 465]] )
receive = str(input('Receiver: '))
subject = str(input('Subject: '))
message = str(input('Message: '))
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person <johnappleseed3113#gmailc.om>
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
you should remove tab below.
sender = 'johnappleseed3113#gmail.com'
receivers = ['to#todomain.com']
message = """From: From Person
To: To Person <"""receive""">
Subject: """subject"""
"""message"""
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"

Categories