voodoodyne / subethasmtp

SubEtha SMTP is a Java library for receiving SMTP mail
Other
343 stars 138 forks source link

Support nested brackets in EmailUtils.extractEmailAddress #97

Open aepshteyn opened 4 years ago

aepshteyn commented 4 years ago

I'm using Wiser to test the mail functionality of my Google App Engine app and discovered that there is an issue in the Google App Engine SDK's usage of the Python smtplib.SMTP.sendmail function such that when given a FROM header like "Foo Bar <foobar@example.com>", it wraps the address string within another pair of angle brackets and issues an SMTP command like mail FROM:<Foo Bar <foobar@example.com>>, which is unusual, and Wiser returns a 553 / "Invalid email address" response.

I found that changing the address = address.substring(1, address.indexOf('>')) line in org.subethamail.smtp.util.EmailUtils.extractEmailAddress to use lastIndexOf instead of indexOf is a simple solution to the aforementioned problem,

  /**
   * Extracts the email address within a <> after a specified offset.
   */
  public static String extractEmailAddress(String args, int offset) {
    String address = args.substring(offset).trim();
    if (address.indexOf('<') == 0) {
      // address = address.substring(1, address.indexOf('>'));
      // **this patch allows nested angle brackets (e.g. "<Foo Bar <foobar@example.com>>"):**
      address = address.substring(1, address.lastIndexOf('>'));
      // spaces within the <> are also possible, Postfix apparently
      // trims these away:
      return address.trim();
    }

    // find space (e.g. SIZE argument)
    int nextarg = address.indexOf(" ");
    if (nextarg > -1) {
      address = address.substring(0, nextarg).trim();
    }
    return address;
  }

I believe that this change will not break compatibility with the SMTP RFC, which specifies only that:

The <reverse-path> portion of the first or only argument contains the source mailbox (between < and > brackets)

I mean that it doesn't explicitly forbid nested brackets.

My patched code still supports addresses without additional nested brackets (i.e. both MAIL FROM:Foo Bar <foobar@example.com> and MAIL FROM:<Foo Bar <foobar@example.com>> will be accepted.

I realize that the App Engine/Python peculiarity that I described doesn't have anything to do with subethasmtp, but I was wondering if you'd be willing to accept this tiny patch anyways. Would be happy to create a pull request if you accept.

Since Wiser is intended to be used for testing, I think it should be pretty lenient with what it accepts. Another argument in favor of this patch is that Dumbster is able to handle such email addresses without a problem.

davidmoten commented 4 years ago

An actively supported (and released to Maven Central) fork is at https://github.com/davidmoten/subethasmtp. You are welcome to contribute there. See also issue #84.