I tried sending email using python and put attachment, but when it sent the attachment became noname without any extension.
message = MIMEMultipart()
message ['From'] = sender_email
message ['To'] = ', '.join(receiver_email)
message ['Subject'] = 'Python Email'
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'Final Project - Basic Python.pdf'
attach_file = open('Final Project - Basic Python.pdf', 'rb')
payload = MIMEBase('application', 'octate-stream')
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
Related
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
user = 'user#icloud.com'
password = 'apppassword'
host = 'smtp.mail.me.com'
text = 'E-Mail Body'
subject = 'This is a Subject'
to_emails = ['user2#icloud.com']
from_email = 'John Doe <user#icloud.com>'
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = 'user2#icloud.com'
msg['Subject'] = subject
body = MIMEText(text, 'plain')
msg.attach(body)
msg_str = msg.as_string()
server = smtplib.SMTP(host, port=587)
server.starttls()
server.ehlo()
server.login(user, password)
server.sendmail(from_email, to_emails, msg_str)
server.quit()
I am trying to program an email client in python.
At the moment I fail to send via iCloud.
The email only arrives if I send the email to the iCloud mail that sends it. So to myself.
So you could say it's the loneliest email client in the world right now.
But all kidding aside, I don't get it. Is it me? Is it iCloud?
I was working on my discord bot trying to implement a email feature where you imbed a file and then the discord bot downloads it and sends it back out to the server. I came across the issue where I have no idea how I would begin to save the file. You can find my code at https://github.com/Omar-Alabdalla/DiscordBot. the specific files that have the emailing feature are mailFunctions(discord commands part) and basicMail(email commands part).
I looked through the docs of nextcord.py and couldn't find any simple way that I could understand. I probably just missed what I was supposed to find though.
discord command Code:
#commands.command()
async def mailFile(self, ctx, *stuff):
# received if else statement from stackoverflow: https://stackoverflow.com/questions/65169339/download-csv-file-sent-by-user-discord-py
if str(ctx.attachments) == "[]": # This checks if there is an attachment on the message
return "You didn't include a file"
else:
await save("mailFile
The mailing class code:
def sendFileMail(rmail, message):
mail_content = '''Hello,
This is a test mail.
In this mail we are sending some attachments.
The mail is sent using Python SMTP library.
Thank You
'''
# Setup the MIME
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = rmail
message['Subject'] = 'A test mail sent by Python. It has an attachment.'
# The subject line
# The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))
attach_file_name = 'TP_python_prev.pdf'
attach_file = open(attach_file_name, 'rb') # Open the file as binary mode
payload = MIMEBase('application', 'octate-stream')
payload.set_payload(attach_file.read())
encoders.encode_base64(payload) # encode the attachment
# add payload header with filename
payload.add_header('Content-Decomposition', 'attachment', filename=attach_file_name)
message.attach(payload)
# 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_email, password) # login with mail_id and password
text = message.as_string()
session.sendmail(sender_email, rmail, text)
session.quit()
print('Mail Sent')
Apologies for not including code prior First time posting on stack overflow
See Attachment.save: https://nextcord.readthedocs.io/en/latest/api.html?highlight=attachment#nextcord.Attachment.save
for attachment in ctx.message.attachments:
await attachment.save(attachment.filename)
I am currently reading file from azure blob storage and sending email. I would like to add password protection to the attachment.
below is my current code which is sending an email with the attachment
import base64
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType)
from azure.storage.blob import BlockBlobService
# mail details
to = To_address
from_email = From_Address
subject = Subject
content = '''
Test Content'''
# create mail object
message = Mail(
from_email = from_email,
to_emails = to,
subject = subject,
html_content = content
)
# read the content from azure blob storage
blob_service = BlockBlobService(account_name=Blob_Storage_Account, account_key=account_key)
## read the content inside blob
# read export file
export_file_data = blob_service.get_blob_to_bytes(Blob_Container, export_file_name)
export_file_mail_content = export_file_data.content
# create export file attachement
export_file_encoded = base64.b64encode(export_file_mail_content).decode()
export_file_attachment = Attachment()
export_file_attachment.file_content = FileContent(export_file_encoded)
export_file_attachment.file_type = FileType('application/txt')
export_file_attachment.file_name = FileName(export_file_name.split('/')[-1])
message.add_attachment(export_file_attachment)
# send mail with above attachment
try:
mail = SendGridAPIClient(send_grid_api_key)
response = mail.send(message)
except Exception as e:
print(str(e))
any possibilities here to add password to the file which is located in Azure storage before sending email.
I tried with pyminizip but the same is not supporting to my version 3.6. Is there any suggestion apart from open source module?
I'm trying to send an email via the Gmail API using Python, I want to iclude the signature. I'm able to successfuly get the signature using the following funciotn:
def addSignature(service):
sigtanture = service.users().settings().sendAs().get(userId=USER, sendAsEmail='example#example.com').execute()
return sigtanture['signature']
addSignature(SERVICE)
However, at the time of creating the message that I'll send, how do I append the Signature?
def CreateMessage(sender, to, subject, message_text, signature):
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message[???] = signature
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
I'm trying to send the message:
thebody = CreateMessage(USER, 'to#example.com', 'TestSignatureAPI','testing', addSignature(SERVICE))
SendMessage(SERVICE, USER, thebody)
Thank you!
Unfortunately there is no built-in feature to append the Gmail signature to your email
Instead, once you retrieve your signature as a text, you can simply append it manually to the end of your message_text before encoding.
See also here.
Assuming you retrieved the signature correctly and based on your code this means:
def CreateMessage(sender, to, subject, message_text, signature):
message_text = message_text + "\n" + signature
message = MIMEMultipart('alternative')
message['to'] = to
message['from'] = sender
message['subject'] = subject
message.attach(MIMEText(message_text_plain, 'plain'))
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
I am trying to get the content of a ticket via REST-API from OTRS v4 and send the content to an external mail-address.
Everything works fine, except the attachment part. It sends an attachment, but the file is not readable and even has a different size than the source.
Doc for OTRS REST-API (TicketGet): http://doc.otrs.com/doc/api/otrs/5.0/Perl/Kernel/GenericInterface/Operation/Ticket/TicketGet.pm.html
# get the data vie REST from OTRS
TicketID = "12345"
headers = {
"Content-Type": 'application/json'
}
payload = {
'UserLogin': 'user',
"Password": 'pass',
"Extended": '1',
'AllArticles': '1',
'Attachments': '1',
}
url = 'https://somedomain.com/otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/TicketGet/' + TicketID
result = requests.get(url, headers=headers, data=json.dumps(payload))
data = result.json()
# send content of ticket as an email to "soemone#somedmain.com"
email_subject = data['Ticket'][0]['Article'][0]['Subject']
email_body = data['Ticket'][0]['Article'][0]['Body']
msg = MIMEMultipart()
msg['From'] = "noreply#somedomain.com"
msg['To'] = "soemone#somedmain.com"
msg['Subject'] = email_subject
# text
msg.attach(MIMEText(email_body, 'plain'))
# attachment
attachment_content_type = data['Ticket'][0]['Article'][0]['Attachment'][0]['ContentType'] #outputs for example:
attachment_content = data['Ticket'][0]['Article'][0]['Attachment'][0]['Content'] #base64 ?
attachment_filename = data['Ticket'][0]['Article'][0]['Attachment'][0]['Filename'] #outputs for example:
mimetype = attachment_content_type.split(';')[0]
basetype, subtype = mimetype.split('/', 1)
att = MIMEBase(basetype, subtype)
att.set_payload(attachment_file)
att.add_header('Content-Disposition', 'attachment', filename=attachment_filename)
msg.attach(att)
# send msg
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
Looks like this works:
# attachment
attachment_content = data['Ticket'][0]['Article'][0]['Attachment'][0]['Content']
attachment_filename = data['Ticket'][0]['Article'][0]['Attachment'][0]['Filename']
filedata = base64.b64decode(attachment_content)
att = MIMEBase('application', 'octet-stream')
att.set_payload(filedata)
encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment', filename=attachment_filename)
msg.attach(att)
# send msg
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()