Hi Pablo,
As far as I know, unless you what the SMTP gateway on-premises you can't do that.
What you are looking for are doable using Transport agents, but they are not supported in Office 365 or Exchange Online.
Transport agents in Exchange 2013:
https://msdn.microsoft.com/en-us/library/office/dd877026(v=exchg.150).aspx
This is listing all available options across both(some are not availabe online):
Exchange Online and Exchange 2013 development:
Create custom solutions for email, calendar, contacts, and other items that are stored in Exchange Online or on an Exchange 2013 server. You can use Exchange Web Services (EWS), Autodiscover, mail apps for Office, or other APIs to develop your applications.