Search code examples
javaspringgmailgmail-apigoogle-directory-api

Using Gmail aliases to link mail replies to application content


I have the following use case in my app: When a specific event happens in the app all interested users should be notified by email. Then if a user replies to the email, his reply should be shown in the event page in the app.

My initial idea was to create a temp mail alias of the main notification email every time when an event happens and send the notification email with that alias set in the Reply-To header. Then if someone replies to that mail by using the alias (let's say [email protected]) I can figure out which event this reply refers to.

It turned out that Spring's JavaMailSender doesn't provide a way to use aliases, so I tried with Gmail API. As far as I understood creating a Gmail alias means actually setting an already existing email in your domain as an alias for another already existing email in that domain. So the Java code to achieve this using Directory API and Gmail API would look like this:

User newUser = new User();
UserName userName = new UserName();
userName.setGivenName("xsd");
userName.setFamilyName("ewrewr");
newUser.setPrimaryEmail("[email protected]");
newUser.setPassword("12345");
newUser.setName(userName);
User result = directoryService.users().insert(newUser).execute();

SendAs sendAs = new SendAs().setSendAsEmail("[email protected]").setReplyToAddress("[email protected]").setDisplayName("My name").setTreatAsAlias(true);
SendAs sendAsResult = gmailService.users().settings().sendAs().create(user, sendAs).execute();

MimeMessage emailContent = createEmail("[email protected]", "[email protected]", "Test from app", "Test body");
Message message = createMessageWithEmail(emailContent);
message = gmailService.users().messages().send(user, message).execute();

But as far as I know there are some limits on the number of accounts you can create per domain/account and also Google would charge more for this.

Is there another easier way to create aliases in Gmail? Or is there another approach to achieve the desired functionality (linking mail replies to application content) without using mail aliases?


Solution

  • Try leveraging '+' functionality given by Gmail for creating temporary aliases. The basic idea is if my email id is [email protected], I can send/receive an email with [email protected] or [email protected] and it will work like a charm.

    You can utilize this by keeping the alias/unique-id after the '+' in the Gmail id and then parse this alias easily in your application.