Use Python to send SMS as a given name - python

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?

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.

Python variable not updating

Basically I'm creating a program to help with my work. It will send emails to people in an excel list and move down to the next first name and email address in the list until it's done. Heres the code so far
`#AutoMail Version 2
#Goal of new version is to run on any computer. With minimal or no mouse and keyboard input
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Random Variables
sender_address = str(input("Please enter your email address!: "))
sender_pass = str(input("Please enter your email password (No data is stored anywhere!): "))
count = 0
#This prompts user to input the file path of their CSV file.
file_path = "C:/Users/Spring/Documents/test_book_py.csv" #Change to input later!!!!!!
df = pd.read_csv(file_path, usecols=['First Name', 'Email Address'])
amount = int(input("How many emails would you like to send? "))
#Important Variables
cell_value = 0 #Which cell the info is coming from
#Cell Varialbes
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
#Gmail info Variables
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
#Emailing Process Start
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
#Email sending
while count < amount:
session.sendmail(sender_address, receiver_address, text)
cell_value = cell_value + 1
count = count + 1
print(cell_value)`
I've tried every fix I could find online for variables not updating. When I print the "cell_value" varible it prints with the updated value however the other lines in the code specifically lines 21 and 22 use that variable and they aren't using the updated varible so it is always at a constant 0 value when it should be cell_value + 1 every time the loop repeats. Is there a different way I should loop the variable updating? I need it to change that value by +1 every time so that it continues to move down the list. Keep in mind that I am a huge beginner so my code probably looks very confusing.
The issue is updating cell_value doesn't automatically updates all the data that was calculated with cell_value's old value. Once "Hello " + name_cell + ",\n\nThis is a test body" evaluates, for example, the resulting string has no relation to name_cell, and wan't change when name_cell changes. If you want that string to change when name_cell changes, you need to rerun the code that created that string.
For your case here, it looks like you could just loop over the latter half of the code. The closest to what you already have would be:
# i instead of cell_value for clarity
for i in range(amount):
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
Arguably, it would be may be considered more idiomatic to zip the two .values objects that you're looping over, then islice amount-many elements from that, but I think this is cleaner.

Gmail retrive body text cwoth out b'..\r\n exmaple b'message1\r\n'

WIth this script i'd like to retreive messages from gmdail.
The expected output of the script should be message1, message2, message3, message4, message5
But the script print out the following list [b'message1\r\n', b'message2\r\n', b'message3\r\n', b'message4\r\n', b'message5\r\n']
Does anyone can help me on this?
Here is the code snippet:
import imaplib
def read_gmail():
# user and pass for login to gmail server
username = input("Enter Email Address for Login: ").lower()
password = input("Enter password for Login: ").lower()
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
if username == "me" and password == "me":
mail.login('mymail', 'mypass')
else:
mail.login(username, password)
mail.list()
mail.select("Inbox")
status, data = mail.search(None, 'SUBJECT "Enc Message"') # all message with Subject-> Enc Message
minimata = []
clear_lista = []
for num in data[0].split():
status, data = mail.fetch(num, '(BODY.PEEK[TEXT])') # to see the body text
minimata.append(data[0][1]) # apothikeyo se nea lista ta kryprografimena minimata.
for ch in minimata:
clear_lista.append(ch)
return clear_lista
Currently, your minimata list contains byte objects and this is where the leading b' comes from. To get rid of them you just need to decode them.
Regarding, \n and \r, you can use rstrip().
The following should do the trick:
for ch in minimata:
clear_lista.append(ch.rstrip().decode())

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

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.

Send email to many recipients

I need to send an email to 100 recipients. When I send message to one recipient, it takes three seconds. And when I send it to three recipients at once, it also takes three seconds.
So I use multiple recipient to send the message faster.
def send(x, y, z):
to = [x, y, z]
subject="Multi Test"
gmail_user = 'test#gmail.com'
gmail_pwd = 'test'
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
msg = header + '\n' + subject + '\n\n'
smtpserver.sendmail(gmail_user, to, msg)
smtpserver.close()
the email that i want to send message for is
1#yahoo.com, 2#yahoo.com, 3#yahoo.com....., 100#yahoo.com
so i want the script split into threes emails then send the message
or if you know another way to create script to send the message faster
Change your function to
def send(to):
// ..
header = 'To:' + ", ".join(to)
Then call it as
send(["1#yahoo.com", "2#yahoo.com", "3#yahoo.com", ..., "100#yahoo.com"])
But think about the following:
If you do this, every recipient will know that you send the email to all other 99 recipients.
You should use email.message to build an email. Don't just concat strings.

Categories