How to split an email in Python after '#'? - python

I have this piece of code but when you insert an email, the domain does not print fully. Can someone please explain what is wrong with the code and if there is a faster option? (I am new to Python)
email = input ('Enter your email address: ').strip()
at = email.find ('#')
after_at = email.find (' ' , at)
host = email [at+1 : after_at]
print (host)
Ex. abc#gmail.com > gmail.co

You should be able to use str.split:
domain = email.split('#')[-1]

Related

Find a money amount specified in a email and print it next to a str

I've been trying to make an API that automates a detector for new transaction emails in my Gmail Account, and now it detects all the emails coming from my bank that are related to a transaction send to myself, but it prints the whole email (which contains the money expressed like this "$" in a certain point of the email), and I want it that the script detects the money amount and then prints a string with it like this for example
print("Transaction Recieved"," $" ,moneyAmount,"!")
The Messages Filter part of the script
#Messages Filter
message_count = 50
for message in messages[:message_count]:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
email = (msg['snippet'])
if "Datos de la transferencia que recibiste Monto $" in email:
service.users().messages().modify(userId='me', id=message['id'], body={'removeLabelIds': ['UNREAD']}).execute()
print(f'{email}\n')
And I can't figure how to make it so it detects the money amount that is expressed inside the bank's email.
I tried to do an attempt of making it to detect a string pattern of a value of 1 digit that could go from 1 to 9 followed by a "." and after that a value of 3 digits that could go from 001 to 999 and then print the whole value, but it didn't work so I'm out of ideas.
Here's my attempt of making it
#Messages Filter
message_count = 50
for message in messages[:message_count]:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
email = (msg['snippet'])
if "Datos de la transferencia que recibiste Monto $" in email:
value = re.findall(r'$\d{1}.\d{3}', email)
service.users().messages().modify(userId='me', id=message['id'], body={'removeLabelIds': ['UNREAD']}).execute()
print(f'{email}\n')
print(f'{value}\n')
The amount of money is displayed like this in the email
And this is like directly from the email
If someone with an idea could help me, I would be very grateful.
P.S.:Btw if you see something that you don't understand because of the language, it's because it's in Spanish, but it's mostly in strings so it shouldn't be a problem.
I had to replace the string pattern that I was using for the re and it ended like this
re.findall(r'\$\d+(?:.\d{3})+(?:,\d+)?', email)
Insted of this
re.findall(r'$\d{1}.\d{3}', email)
Thanks to #Grismar for the answer

Python printing format using """ """ format

I am writing an email application to send mass emails. In the body of the email I want to insert the first name from a list of names. But I can't seem to figure out why this code isn't working. Any suggestions are most appreciated.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """.format(first_name)
def send_test_email(body):
first_name = 'mike'
print(body)
send_test_email(body)
Output:
Dear ,
Here is new email.
Thanks.
Mike
You have already assigned what body is. So even if you change value of parameter (first_name) in format later, it does not affect the original body.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """
def send_test_email(body):
first_name = 'mike'
print(body.format(first_name))
send_test_email(body)
# Dear mike,
# Here is new email.
# Thanks.
# Mike

send multiple record to a particular user by mail

I need to send mail to particular user from the database. i have data table where 1000 of records are available. each record have some email ids. or some id has assigned to multiple record . i need to send record to the particular email only.
I have form from where i used to select company name and strt date. from these i fetch all the value into list. now worries is how to send record to particular user
let my code example
def sendmail():
form = SQLFORM.factory(Field('select_company', db.company, represent=lambda c, row:get_company_name(c), requires = IS_IN_DB(db,'company.id','%(company)s')),
Field('choose_start_date','date',requires=IS_NOT_EMPTY(error_message='Please choose Start Date')),
Field('choose_end_date','date',requires=IS_NOT_EMPTY(error_message='Please choose end Date')))
if form.accepts(request,session):
session.company = form.vars.select_company
session.strtdate = form.vars.choose_start_date
session.enddate = form.vars.choose_end_date
mailidr()
return dict(form=form)
def mailidr():
from gluon.tools import Mail,datetime
mail=Mail()
#specify server
mail=auth.settings.mailer
mail.settings.server='smtp.gmail.com:587'
mail.settings.login='comdummy09#gmail.com:critical#009'
#specify address to send as
mail.settings.sender='comdummy09#gmail.com'
#send the message
list = []
for row in db((db.tracker.company == session.company) & (db.tracker.Complience_Status != 1) & (db.tracker.periodicity_due_date >= session.strtdate) & (db.tracker.periodicity_due_date <= session.enddate)).select():
list.append('<tr><td style="padding-top:5px;padding-bottom:5px;padding-right:5px;padding-left:5px;">'+row.Compliance_Area+'</td><td style="padding-top:5px;padding-bottom:5px;padding-right:5px;padding-left:5px;">'+row.law_description+'</td><td style="padding-top:5px;padding-bottom:5px;padding-right:5px;padding-left:5px;" >'''+row.activity_name+'''</td><td style="padding-top:5px;padding-bottom:5px;padding-right:5px;padding-left:5px;">'+str(row.periodicity_due_date)+'</td></tr>')
mail.send(to=[row.client_owner],
subject='Compliance and Due_Date',
message='<html>'
'<body>'
'<h1>Test Mails</h1>'
'<h2>Dear \t' +session.company+ '</h2>'
'</br><h3>REMINDER</h3>'
'<p>Please note that the fol1ing records are due between ' +session.strtdate+ ' to ' +session.enddate+ '</p>'
'<table border=1>'
'<thead >'
'<tr>'
'<th style="padding-top:5px;padding-bottom:5px;padding-right:5px;padding-left:5px;">Compliance Area</th>'
'<th>record</th><th>date (Due Date)</th>'
'</tr>'
'</thead>'
'<tbody>'
+str(list)+
'</tbody>'
'</table>'
'</body>'
'</html>')
response.flash='mail send'
return ''
from this code i a able to send mail. but problem is that user get n no mails
if i used to take mail.send to out side the function its not work
from the docs (http://www.web2py.com/books/default/chapter/29/08/emails-and-sms#Setting-up-email)
Mail returns True if it succeeds in sending the email and False
otherwise. A complete argument list for mail.send() is as follows:
So, for a test you should try capturing the response - e.g. change:
mail.send(to=[row.client_owner],
to
mail_response = mail.send(to=[row.client_owner],
and then return locals() instead of "" so you can see in a test page what (if any) failure you are getting in the send. this is just for testing...
A permanent alternate method is shows here: i am trying send email using web2py with gmail and using smtp setting i have attached all code

Multiple arguments in MySQL raw() query in DJango-Python

I need to find a person when he enters his mobile number or email in the login form.
My raw() query goes like this:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',[login_id],[login_id])
But I am always getting a error:
Exception Value: not enough arguments for format string
So, what's the correct format for getting this solved?
You should put parameters under the same list:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',
[mobile, email])
There is no need for a raw query here.
users = User.objects.filter(Q(mobile=login_id) | Q(email=login_id))
You can do this by any of these two ways as already said above:
from django.db.models import Q
users = User.objects.filter(Q(mobile=login_id) | Q(email=login_id))
or by using raw() method:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',[login_id,login_id])
The upper solutions were not working for me. I solved by this in Python 3
user = Users.objects.raw("SELECT * FROM main_users WHERE mobile = '%s' OR email = '%s' " %(mobile, email))

Find a way to add a string to a tuple

y="Peter Email: peter#rp.com Phone: 91291212"
z="Alan Email: alan#rp.com Phone: 98884444"
w="John Email: john#rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details" into the add_book. I also found that I cannot use append because its a tuple.
details = raw_input("Enter name in the following format: name Email: Phone:")
print "New contact added"
print details
if details in add_book:
o=add_book+details
print "contact found"
print details
print add_book
address_book = {}
address_book['Alan'] = ['alan#rp.com, 91234567']#this is what I was supposed to do:
#but when I print it out, the output I get is:
{'Alan': ['alan#rp.com, 91234567']} #but I want to remove the '' and {}
I am still an amateur in programming with python so I really need all the help I can get, thanks:)!!
A simple fix would be to use a list instead of a tuple. You can do this by changing your initialization of add_book from:
add_book=str(y) ,"" + str(z) ,"" + str(w)
to:
add_book = [y,z,w]
#No need to call str() every time because your data are already strings
However, wouldn't it make more sense to organize your data as a list of dictionaries? For example:
contacts = ["Peter", "Alan", "John"]
addr_book = [len(contacts)]
for i in range(len(contacts)):
contact = contacts[i]
email= raw_input(contact+"'s email: ")
phone= raw_input(contact+"'s phone: ")
addr_book[i] = {'name':contact, 'email':email, 'phone':phone}
FURTHERMORE:
If I understood your question correctly, you have specific requirements as to how the output of your program should look. If you use the above data format, you can create whatever output you like. for example, this code
def printContact(contact):
print contact['name']+': ['+contact[email]+','+contact[phone]+']'
will output something like:
Alan: [alan#email.com,555-555-5555]
Of course you can change it however you like.
firstly [] is a list. a tuple is (,);
so what you want is
address_book['Alan'] = ('alan#rp.com', '91234567')
But this seems quite odd. What i would do is create a class
class Contact(object):
name = "Contact Name"
email = "Contact Email"
ph_number = "00000000"
def __str__(self):
return "%S: %s, %s" % (self.name, self.email, self.ph_number)
then
address_book = []
contact_alan = Contact()
contact_alan.name = "Alan"
contact_alan.email = "alan#rp.com"
contact_alan.ph_number = "91234567"
print contact
(not next to a machine with python so it might be slightly wrong. Will test it when i can get to one.)
EDIT:- as Paul pointed out in his comment:
class Contact(object):
def __init__(self, name, email, ph_number):
self.name = name
self.email = email
self.ph_number = ph_number
contact_alan = Contact(name="Alan", email = "alan#rp.com", ph_number="91234567")

Categories

Resources