jeremyephron / simplegmail

A simple Gmail API client for applications in Python
MIT License
348 stars 74 forks source link

Forward an existing email to other recipients #18

Open PrashantSrivastava4 opened 3 years ago

PrashantSrivastava4 commented 3 years ago

Can somebody help me with code to forward an existing email to other recipients using simplegmail python library?

PrashantSrivastava4 commented 3 years ago

Can somebody help me with code to forward an existing email to other recipients using simplegmail python library?

roib20 commented 3 years ago

As far as I'm aware there's no built-in Forward function. However, I wrote a short script that should work (I tested it and it works for me). See the code snippet below; to use it, you only need to replace the first three variables for your usage (see comments). It does not have a command-line interface but you could adapt it for that.

from simplegmail import Gmail

your_email = "you@gmail.com"  # Replace with your email
qry = "Example message label:Fwd"  # Write here a query that finds any messages that you want to forward
recipients = "john@gmail.com, jane@gmail.com"  # Write here the emails of any recpients you want to send the messages to

gmail = Gmail()

messages = gmail.get_messages(query=qry)

for message in messages:
    msg_subject = message.subject
    try:
        msg_body = message.html
    except TypeError:
        continue

    params = {
        "to": recipients,
        "sender": "me@myemail.com",
        "subject": "Fwd: "+str(msg_subject),
        "msg_html": msg_body,
        "signature": True  # use my account signature
    }

    message = gmail.send_message(**params)
jeremyephron commented 3 years ago

There is no forward function since forwarding is client defined behavior (i.e., its a series of actions that is dependent on the mail client you use). Forwarding generally involves taking the body of a message, prepending something to that message, changing the subject, and sending that message to someone else. All these actions can be done with the simplegmail library: access the body with message.html (if the html version of the message exists), prepend something with forward_str + message.html where forward_str is whatever string you'd like to prepend, and the subject and recipient in the standard way.

The script @roib20 wrote above will change the subject line and send the body of the message to a new recipient. The only logic you might like to add is creating a string to prepend that may contain information about the original sender, recipient, date, and subject like you would see in typical email clients. All of these pieces of information can be accessed from the simplegmail message object.

jeremyephron commented 3 years ago

I'm redoing the documentation in the wiki at the moment to be much more thorough. I will include an example of forwarding there based on this issue.