Skip to content

Commit af0d5f2

Browse files
bretmcglesv
authored andcommitted
Added JavaMail API examples for App Engine (#208)
* Added JavaMail API examples for App Engine * Added BounceHandlerServlet and HandleEmailDiscussion.java
1 parent 25713c9 commit af0d5f2

File tree

10 files changed

+613
-0
lines changed

10 files changed

+613
-0
lines changed

appengine/mail/README.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# JavaMail API Email Sample for Google App Engine Standard Environment
2+
3+
This sample demonstrates how to use [JavaMail][javamail-api] on [Google App Engine
4+
standard environment][ae-docs].
5+
6+
See the [sample application documentaion][sample-docs] for more detailed
7+
instructions.
8+
9+
[ae-docs]: https://cloud.google.com/appengine/docs/java/
10+
[javamail-api]: http://javamail.java.net/
11+
[sample-docs]: https://cloud.google.com/appengine/docs/java/mail/
12+
13+
## Setup
14+
1. Update the `<application>` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
15+
with your project name.
16+
1. Update the `<version>` tag in `src/main/webapp/WEB-INF/appengine-web.xml`
17+
with your version name.
18+
19+
## Running locally
20+
$ mvn appengine:devserver
21+
22+
## Deploying
23+
$ mvn appengine:update

appengine/mail/pom.xml

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<!--
2+
Copyright 2016 Google Inc. All Rights Reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
-->
16+
<project>
17+
<modelVersion>4.0.0</modelVersion>
18+
<packaging>war</packaging>
19+
<version>1.0-SNAPSHOT</version>
20+
<groupId>com.example.appengine</groupId>
21+
<artifactId>appengine-mail</artifactId>
22+
23+
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
24+
<parent>
25+
<groupId>com.google.cloud</groupId>
26+
<artifactId>doc-samples</artifactId>
27+
<version>1.0.0</version>
28+
<relativePath>../..</relativePath>
29+
</parent>
30+
31+
<dependencies>
32+
<dependency>
33+
<groupId>javax.servlet</groupId>
34+
<artifactId>servlet-api</artifactId>
35+
<type>jar</type>
36+
<scope>provided</scope>
37+
</dependency>
38+
<dependency>
39+
<groupId>com.google.appengine</groupId>
40+
<artifactId>appengine-api-1.0-sdk</artifactId>
41+
</dependency>
42+
<dependency>
43+
<groupId>javax.mail</groupId>
44+
<artifactId>mail</artifactId>
45+
<version>1.4.7</version>
46+
</dependency>
47+
</dependencies>
48+
<build>
49+
<!-- for hot reload of the web application -->
50+
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
51+
<plugins>
52+
<plugin>
53+
<groupId>org.apache.maven.plugins</groupId>
54+
<version>3.3</version>
55+
<artifactId>maven-compiler-plugin</artifactId>
56+
<configuration>
57+
<source>1.7</source>
58+
<target>1.7</target>
59+
</configuration>
60+
</plugin>
61+
<!-- Parent POM defines ${appengine.sdk.version} (updates frequently). -->
62+
<plugin>
63+
<groupId>com.google.appengine</groupId>
64+
<artifactId>appengine-maven-plugin</artifactId>
65+
<version>${appengine.sdk.version}</version>
66+
</plugin>
67+
</plugins>
68+
</build>
69+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.appengine.mail;
18+
19+
// [START bounce_handler_servlet]
20+
import com.google.appengine.api.mail.BounceNotification;
21+
import com.google.appengine.api.mail.BounceNotificationParser;
22+
23+
import java.io.IOException;
24+
import java.util.logging.Logger;
25+
import javax.mail.MessagingException;
26+
import javax.servlet.http.HttpServlet;
27+
import javax.servlet.http.HttpServletRequest;
28+
import javax.servlet.http.HttpServletResponse;
29+
30+
public class BounceHandlerServlet extends HttpServlet {
31+
32+
private static final Logger log = Logger.getLogger(BounceHandlerServlet.class.getName());
33+
34+
@Override
35+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
36+
try {
37+
BounceNotification bounce = BounceNotificationParser.parse(req);
38+
log.warning("Bounced email notification.");
39+
// The following data is available in a BounceNotification object
40+
// bounce.getOriginal().getFrom()
41+
// bounce.getOriginal().getTo()
42+
// bounce.getOriginal().getSubject()
43+
// bounce.getOriginal().getText()
44+
// bounce.getNotification().getFrom()
45+
// bounce.getNotification().getTo()
46+
// bounce.getNotification().getSubject()
47+
// bounce.getNotification().getText()
48+
// ...
49+
} catch (MessagingException e) {
50+
// ...
51+
}
52+
}
53+
}
54+
// [END bounce_handler_servlet]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.appengine.mail;
18+
19+
// [START example]
20+
import javax.mail.internet.MimeMessage;
21+
import javax.servlet.http.HttpServletRequest;
22+
import javax.servlet.http.HttpServletResponse;
23+
import javax.servlet.ServletException;
24+
import java.util.logging.Logger;
25+
import java.util.regex.Matcher;
26+
27+
public class HandleDiscussionEmail extends MailHandlerBase {
28+
29+
private static final Logger log = Logger.getLogger(HandleDiscussionEmail.class.getName());
30+
public HandleDiscussionEmail() { super("discuss-(.*)@(.*)"); }
31+
32+
@Override
33+
protected boolean processMessage(HttpServletRequest req, HttpServletResponse res)
34+
throws ServletException
35+
{
36+
log.info("Received e-mail sent to discuss list.");
37+
MimeMessage msg = getMessageFromRequest(req);
38+
Matcher match = getMatcherFromRequest(req);
39+
// ...
40+
return true;
41+
}
42+
}
43+
// [END example]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.appengine.mail;
18+
19+
import javax.mail.internet.MimeMessage;
20+
import javax.mail.MessagingException;
21+
import javax.mail.Session;
22+
import javax.servlet.Filter;
23+
import javax.servlet.FilterChain;
24+
import javax.servlet.FilterConfig;
25+
import javax.servlet.http.HttpServletRequest;
26+
import javax.servlet.http.HttpServletResponse;
27+
import javax.servlet.ServletException;
28+
import javax.servlet.ServletRequest;
29+
import javax.servlet.ServletResponse;
30+
import java.io.IOException;
31+
import java.util.Properties;
32+
import java.util.regex.Matcher;
33+
import java.util.regex.Pattern;
34+
35+
/**
36+
* Base class for handling the filtering of incoming emails in App Engine.
37+
*/
38+
// [START example]
39+
public abstract class MailHandlerBase implements Filter {
40+
41+
private Pattern pattern = null;
42+
43+
protected MailHandlerBase(String pattern) {
44+
if (pattern == null || pattern.trim().length() == 0)
45+
{
46+
throw new IllegalArgumentException("Expected non-empty regular expression");
47+
}
48+
this.pattern = Pattern.compile("/_ah/mail/"+pattern);
49+
}
50+
51+
@Override public void init(FilterConfig config) throws ServletException { }
52+
53+
@Override public void destroy() { }
54+
55+
/**
56+
* Process the message. A message will only be passed to this method
57+
* if the servletPath of the message (typically the recipient for
58+
* appengine) satisfies the pattern passed to the constructor. If
59+
* the implementation returns false, control is passed
60+
* to the next filter in the chain. If the implementation returns
61+
* true, the filter chain is terminated.
62+
*
63+
* The Matcher for the pattern can be retrieved via
64+
* getMatcherFromRequest (e.g. if groups are used in the pattern).
65+
*/
66+
protected abstract boolean processMessage(HttpServletRequest req, HttpServletResponse res) throws ServletException;
67+
68+
@Override
69+
public void doFilter(ServletRequest sreq, ServletResponse sres, FilterChain chain)
70+
throws IOException, ServletException {
71+
72+
HttpServletRequest req = (HttpServletRequest) sreq;
73+
HttpServletResponse res = (HttpServletResponse) sres;
74+
75+
MimeMessage message = getMessageFromRequest(req);
76+
Matcher m = applyPattern(req);
77+
78+
if (m != null && processMessage(req, res)) {
79+
return;
80+
}
81+
82+
chain.doFilter(req, res); // Try the next one
83+
84+
}
85+
86+
private Matcher applyPattern(HttpServletRequest req) {
87+
Matcher m = pattern.matcher(req.getServletPath());
88+
if (!m.matches()) m = null;
89+
90+
req.setAttribute("matcher", m);
91+
return m;
92+
}
93+
94+
protected Matcher getMatcherFromRequest(ServletRequest req) {
95+
return (Matcher) req.getAttribute("matcher");
96+
}
97+
98+
protected MimeMessage getMessageFromRequest(ServletRequest req) throws ServletException {
99+
MimeMessage message = (MimeMessage) req.getAttribute("mimeMessage");
100+
if (message == null) {
101+
try {
102+
Properties props = new Properties();
103+
Session session = Session.getDefaultInstance(props, null);
104+
message = new MimeMessage(session, req.getInputStream());
105+
req.setAttribute("mimeMessage", message);
106+
107+
} catch (MessagingException e) {
108+
throw new ServletException("Error processing inbound message", e);
109+
} catch (IOException e) {
110+
throw new ServletException("Error processing inbound message", e);
111+
}
112+
}
113+
return message;
114+
}
115+
}
116+
// [END example]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.appengine.mail;
18+
19+
// [START mail_handler_servlet]
20+
import java.io.IOException;
21+
import java.util.logging.Logger;
22+
import java.util.Properties;
23+
24+
import javax.mail.MessagingException;
25+
import javax.mail.Session;
26+
import javax.mail.internet.MimeMessage;
27+
28+
import javax.servlet.http.HttpServlet;
29+
import javax.servlet.http.HttpServletRequest;
30+
import javax.servlet.http.HttpServletResponse;
31+
32+
public class MailHandlerServlet extends HttpServlet {
33+
34+
private static final Logger log = Logger.getLogger(MailHandlerServlet.class.getName());
35+
36+
@Override
37+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
38+
Properties props = new Properties();
39+
Session session = Session.getDefaultInstance(props, null);
40+
try {
41+
MimeMessage message = new MimeMessage(session, req.getInputStream());
42+
log.info("Received mail message.");
43+
} catch (MessagingException e) {
44+
// ...
45+
}
46+
// ...
47+
}
48+
}
49+
// [END mail_handler_servlet]

0 commit comments

Comments
 (0)