summaryrefslogtreecommitdiff
path: root/src/main/java/com/p4square/grow/backend/SESNotificationService.java
blob: b42d09b2fe8e90dcfeb5edc45db2352195d937a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.p4square.grow.backend;

import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.*;
import com.p4square.grow.config.Config;
import com.p4square.grow.config.ConfigCredentialProvider;
import org.apache.log4j.Logger;

/**
 * Send Notifications via SimpleEmailService.
 */
public class SESNotificationService implements NotificationService {

    private final static Logger LOG = Logger.getLogger(SESNotificationService.class);

    private final AmazonSimpleEmailService mClient;
    private final String mSourceAddress;
    private final Destination mDestination;

    public SESNotificationService(final Config config) {
        this(config, new AmazonSimpleEmailServiceClient(new ConfigCredentialProvider(config)));

        // Set the AWS region.
        String region = config.getString("awsRegion");
        if (region != null) {
            mClient.setRegion(Region.getRegion(Regions.fromName(region)));
        }
    }

    public SESNotificationService(Config config, AmazonSimpleEmailService client) {
        mClient = client;

        mSourceAddress = config.getString("notificationSourceEmail");

        final String[] dests = config.getString("notificationEmail", "").split(",");
        mDestination = new Destination().withToAddresses(dests);
    }

    @Override
    public void sendNotification(final String message) {
        try {
            if (mSourceAddress == null || mDestination == null) {
                // Disable notifications if there is no source address configured.
                LOG.debug("Notifications are disabled because source or destination emails are not configured.");
                return;
            }

            Message msg = new Message()
                    .withSubject(new Content().withCharset("UTF-8").withData("Grow Notification"))
                    .withBody(new Body()
                            .withText(new Content().withCharset("UTF-8").withData(message)));

            SendEmailRequest request = new SendEmailRequest()
                    .withDestination(mDestination)
                    .withSource(mSourceAddress)
                    .withMessage(msg);

            mClient.sendEmail(request);

        } catch (Exception e) {
            LOG.warn("Failed to send notification email", e);
        }
    }
}