Gmail has a nasty habit: if you use Gmail with your own domain, and you send an email to yourself at that domain, the email will not appear in your inbox. It will only appear in your Sent folder, as if you had never received it. Here is how to defeat this behavior using a tiny relay which runs for free on Cloudflare.
The problem
Sending an email to yourself is one of the oldest and simplest ways of leaving a note for your future self. You send it, and it shows up in your inbox, unread, staring at you until you deal with it.
With Gmail, it depends on the addresses. Consider the following scenario:
- Your Gmail account is
alice@gmail.com - You own the domain
alice.example - You have, of course, configured
alice@alice.exampleto forward toalice@gmail.com - You have, of course, configured Gmail to send mail as
alice@alice.example.
Under this scenario, here is what happens when you send an email to yourself:
| From | To | Appears in your inbox? |
|---|---|---|
alice@gmail.com | alice@gmail.com | Yes |
alice@alice.example | alice@gmail.com | Yes |
alice@gmail.com | alice@alice.example | No, only in Sent |
alice@alice.example | alice@alice.example | No, only in Sent |
In other words:
- if you address the email to Gmail, the email arrives at your Inbox, as expected; however:
- if you address it to your own domain, Gmail sabotages you by skipping the Inbox and placing the email in Sent.
...which is precisely the opposite of the reason why you sent that email to yourself.
There is no setting for turning this off. Filters do not help either.
The solution
If Gmail refuses to deliver an email that it recognizes, then Gmail must be given an email that it does not recognize.
The solution is a relay: a small program which receives your email, makes a new email with the same content, and sends that new email to your Gmail address. As far as Gmail can tell, the new email comes from somebody else, so it goes in the Inbox, like any other email.
In this example:
alice@gmail.comis your Gmail address.alice@alice.exampleis the address that you send as.myself@alice.exampleis a new address, which exists only for this purpose.
You send an email to myself@alice.example, and it shows up in the Inbox of alice@gmail.com, with myself@alice.example as the sender.
You will need a domain whose email is handled by Cloudflare Email Routing. Everything else can be done on the Cloudflare web site, under the free plan, with nothing to install on your computer.
How to set it up
- In Cloudflare, go to Email Service | Email Routing | Destination addresses and make sure that
alice@gmail.comis listed as verified. - Go to Workers & Pages, create an application, choose Start with Hello World!, give it a name, and click Deploy.
- In the settings of the new Worker, under Bindings, click Add binding, choose Email Service, and name the variable
EMAIL. - Click Edit code, replace all of the code with the code below, changing the addresses at the top to your own, and click Deploy.
- Go to Email Service | Email Routing | Routing rules and create a routing rule which sends
myself@alice.exampleto your Worker. Your existing rules and your catch-all can stay exactly as they are. - Wait a few minutes, because the new rule does not take effect immediately, and then send an email to
myself@alice.example. - The email should arrive in the Inbox of
alice@gmail.com, withmyself@alice.exampleas the sender.
Here is the code:
import { EmailMessage } from "cloudflare:email";
const relayAddress = "myself@alice.example";
const destinationAddress = "alice@gmail.com";
const allowedSenderSet = new Set( [ "alice@alice.example", "alice@gmail.com" ] );
const copiedHeaderNameSet = new Set( [ "subject", "date", "mime-version", "content-type", "content-transfer-encoding" ] );
const lineBreak = "\r\n";
const headerSectionTerminator = new TextEncoder().encode( lineBreak + lineBreak );
function addressFromHeaderValue( headerValue )
{
const angleBracketMatch = headerValue.match( /<([^>]+)>/ );
const address = angleBracketMatch === null ? headerValue : angleBracketMatch[1];
return address.trim().toLowerCase();
}
function headerSectionLengthFromBytes( messageBytes )
{
for( let index = 0; index <= messageBytes.length - headerSectionTerminator.length; index++ )
if( headerSectionTerminator.every( ( byte, offset ) => messageBytes[index + offset] === byte ) )
return index;
throw new Error( "The message has no end of headers." );
}
function headerLineArrayFromText( headerSectionText )
{
return headerSectionText.split( /\r\n(?![ \t])/ );
}
function relayedBytesFromOriginalBytes( originalBytes, originalFromHeaderValue )
{
const headerSectionLength = headerSectionLengthFromBytes( originalBytes );
const headerSectionText = new TextDecoder().decode( originalBytes.subarray( 0, headerSectionLength ) );
const copiedHeaderLineArray = headerLineArrayFromText( headerSectionText )
.filter( line => copiedHeaderNameSet.has( line.substring( 0, line.indexOf( ":" ) ).trim().toLowerCase() ) );
const newHeaderLineArray = [
`From: ${relayAddress}`,
`To: ${destinationAddress}`,
`Reply-To: ${originalFromHeaderValue}`,
`Message-ID: <${crypto.randomUUID()}@alice.example>`,
...copiedHeaderLineArray
];
const newHeaderBytes = new TextEncoder().encode( newHeaderLineArray.join( lineBreak ) );
const bodyBytes = originalBytes.subarray( headerSectionLength );
const relayedBytes = new Uint8Array( newHeaderBytes.length + bodyBytes.length );
relayedBytes.set( newHeaderBytes, 0 );
relayedBytes.set( bodyBytes, newHeaderBytes.length );
return relayedBytes;
}
export default {
async email( message, environment )
{
const originalFromHeaderValue = message.headers.get( "from" ) ?? "";
const headerSender = addressFromHeaderValue( originalFromHeaderValue );
const envelopeSender = message.from.toLowerCase();
if( !allowedSenderSet.has( envelopeSender ) && !allowedSenderSet.has( headerSender ) )
{
message.setReject( "This address accepts mail only from its owner." );
return;
}
const originalBytes = new Uint8Array( await new Response( message.raw ).arrayBuffer() );
const relayedBytes = relayedBytesFromOriginalBytes( originalBytes, originalFromHeaderValue );
const relayedStream = new Response( relayedBytes ).body;
const relayedMessage = new EmailMessage( relayAddress, destinationAddress, relayedStream );
await environment.EMAIL.send( relayedMessage );
}
};
What the code does
- It refuses any email that does not come from one of the addresses in
allowedSenderSet, because otherwise anyone who discovers the relay address could use it to put things in your inbox. - It gives the new email a new
Message-ID:, a newFrom:, and a newTo:, and it copies only the subject, the date, and the headers that describe the content. Everything else is left out, includingIn-Reply-To:,References:, and the signatures of the original email, so that Gmail is given nothing by which to recognize it. - It places the original sender in
Reply-To:, so that the original sender is not lost. - It copies the body byte by byte, without parsing it. Thus, formatting and attachments arrive intact, no library is needed, and the code should stay within the 10 milliseconds of CPU time that the free plan of Cloudflare Workers allows, even when the attachments are large.
The only thing you need to remember is to address those emails to myself@alice.example instead of alice@alice.example. It is a small price to pay for getting your own mail delivered to you.
Do not touch the To: header
You might be tempted to change the worker and make it put myself@alice.example or alice@alice.example in the To: header, instead of alice@gmail.com. In theory, it should not matter; however, in practice, it fails: the email does not show-up in the Inbox, it only goes in Sent. Gmail does something fishy there.
A note on authorship: This post, along with all of the code in it, was written by Claude, the AI from Anthropic, according to my instructions. The need for this relay was mine. We planned it together, with Claude coming up with most of the solution; we did the troubleshooting together, with Claude doing most of the grunt work. I have read the text of the post, and I have skimmed through the code, but I have not studied it. What I can tell you is that the relay has been tested, and it works.
Comments are disabled until you accept functional cookies.