Skip to content

Commit

Permalink
#15 add mailgun rest api support + fi bug when sending ticket the fir…
Browse files Browse the repository at this point in the history
…st time, the 'to' field was empty because the unupdated ticket object was used
  • Loading branch information
syjer committed Dec 20, 2014
1 parent a44bebb commit 0bd9bf4
Show file tree
Hide file tree
Showing 6 changed files with 295 additions and 119 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,12 @@
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.1.0</version>
</dependency>

<dependency>
<groupId>com.insightfullogic</groupId>
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/alfio/manager/TicketReservationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ public void updateTicketOwner(Ticket ticket,
locale.getLanguage());

if (!StringUtils.equalsIgnoreCase(newEmail, ticket.getEmail()) || !StringUtils.equalsIgnoreCase(newFullName, ticket.getFullName())) {
sendTicketByEmail(ticket, locale, event, confirmationTextBuilder, pdfTemplateBuilder);
sendTicketByEmail(ticketRepository.findByUUID(ticket.getUuid()), locale, event, confirmationTextBuilder, pdfTemplateBuilder);

This comment has been minimized.

Copy link
@syjer

syjer Dec 20, 2014

Author Member

The bug was here.

}

if (StringUtils.isNotBlank(ticket.getEmail()) && !StringUtils.equalsIgnoreCase(newEmail, ticket.getEmail())) {
Expand Down
137 changes: 19 additions & 118 deletions src/main/java/alfio/manager/system/DefaultMailer.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,143 +16,44 @@
*/
package alfio.manager.system;

import alfio.model.system.ConfigurationKeys;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ArrayUtils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.mail.MailException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

import javax.activation.FileTypeMap;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.Properties;
import alfio.model.system.ConfigurationKeys;

@Log4j2
@Component
@Profile("!dev")
public class DefaultMailer implements Mailer {

private final ConfigurationManager configurationManager;
private final Map<String, Mailer> mailers;
private final Mailer defaultMailer;

@Autowired
public DefaultMailer(ConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
this.mailers = new HashMap<>();
this.defaultMailer = new SmtpMailer(configurationManager);
mailers.put("smtp", defaultMailer);
mailers.put("mailgun", new MailgunMailer(configurationManager));
}

@Override
public void send(String to, String subject, String text, Optional<String> html, Attachment... attachments) {

MimeMessagePreparator preparator = (mimeMessage) -> {
MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments) ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
: new MimeMessageHelper(mimeMessage, "UTF-8");
message.setSubject(subject);
message.setFrom(configurationManager.getRequiredValue(ConfigurationKeys.SMTP_FROM_EMAIL));
message.setTo(to);
if (html.isPresent()) {
message.setText(text, html.get());
} else {
message.setText(text, false);
}

if (attachments != null) {
for (Attachment a : attachments) {
message.addAttachment(a.getFilename(), a.getSource(), a.getContentType());
}
}

message.getMimeMessage().saveChanges();
message.getMimeMessage().removeHeader("Message-ID");
};
toMailSender().send(preparator);
}

private JavaMailSender toMailSender() {
JavaMailSenderImpl r = new CustomJavaMailSenderImpl();
r.setDefaultEncoding("UTF-8");
r.setHost(configurationManager.getRequiredValue(ConfigurationKeys.SMTP_HOST));
r.setPort(Integer.valueOf(configurationManager.getRequiredValue(ConfigurationKeys.SMTP_PORT)));
r.setProtocol(configurationManager.getRequiredValue(ConfigurationKeys.SMTP_PROTOCOL));
r.setUsername(configurationManager.getStringConfigValue(ConfigurationKeys.SMTP_USERNAME, null));
r.setPassword(configurationManager.getStringConfigValue(ConfigurationKeys.SMTP_PASSWORD, null));
public void send(String to, String subject, String text,
Optional<String> html, Attachment... attachments) {

String properties = configurationManager.getStringConfigValue(ConfigurationKeys.SMTP_PROPERTIES, null);
String mailerType = configurationManager.getStringConfigValue(
ConfigurationKeys.MAILER_TYPE, "smtp").toLowerCase(
Locale.ENGLISH);

if (properties != null) {
try {
Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ByteArrayResource(
properties.getBytes("UTF-8")), "UTF-8"));
r.setJavaMailProperties(prop);
} catch (IOException e) {
log.warn("error while setting the mail sender properties", e);
}
}
return r;
mailers.getOrDefault(mailerType, defaultMailer).send(to, subject, text,
html, attachments);
}

static class CustomMimeMessage extends MimeMessage {

private String defaultEncoding;
private FileTypeMap defaultFileTypeMap;

CustomMimeMessage(Session session, String defaultEncoding, FileTypeMap defaultFileTypeMap) {
super(session);
this.defaultEncoding = defaultEncoding;
this.defaultFileTypeMap = defaultFileTypeMap;
}

CustomMimeMessage(Session session, InputStream contentStream) throws MessagingException {
super(session, contentStream);
}

public final String getDefaultEncoding() {
return this.defaultEncoding;
}

public final FileTypeMap getDefaultFileTypeMap() {
return this.defaultFileTypeMap;
}

@Override
protected void updateMessageID() throws MessagingException {
removeHeader("Message-Id");
}

@Override
public void setHeader(String name, String value) throws MessagingException {
if(!"Message-Id".equals(name)) {
super.setHeader(name, value);
}
}
}

static class CustomJavaMailSenderImpl extends JavaMailSenderImpl {
@Override
public MimeMessage createMimeMessage() {
return new CustomMimeMessage(getSession(), getDefaultEncoding(), getDefaultFileTypeMap());
}

@Override
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
try {
return new CustomMimeMessage(getSession(), contentStream);
}
catch (MessagingException ex) {
throw new MailParseException("Could not parse raw MIME content", ex);
}
}
}
}
112 changes: 112 additions & 0 deletions src/main/java/alfio/manager/system/MailgunMailer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* This file is part of alf.io.
*
* alf.io is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alf.io is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with alf.io. If not, see <http://www.gnu.org/licenses/>.
*/
package alfio.manager.system;

import java.io.IOException;
import java.util.Optional;

import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.StreamUtils;

import alfio.model.system.ConfigurationKeys;

import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

@Log4j2
@AllArgsConstructor
public class MailgunMailer implements Mailer {

private final OkHttpClient client = new OkHttpClient();
private final ConfigurationManager configurationManager;


private RequestBody prepareBody(String to, String subject, String text,
Optional<String> html, Attachment... attachments)
throws IOException {

String from = configurationManager
.getRequiredValue(ConfigurationKeys.MAILGUN_FROM);

if (ArrayUtils.isEmpty(attachments)) {
FormEncodingBuilder builder = new FormEncodingBuilder()
.add("from", from).add("to", to).add("subject", subject)
.add("text", text);
html.ifPresent((htmlContent) -> builder.add("html", htmlContent));
return builder.build();

} else {
// https://github.com/square/okhttp/blob/parent-2.1.0/samples/guide/src/main/java/com/squareup/okhttp/recipes/PostMultipart.java
MultipartBuilder multipartBuilder = new MultipartBuilder()
.type(MultipartBuilder.FORM);

multipartBuilder.addFormDataPart("from", from)
.addFormDataPart("to", to)
.addFormDataPart("subject", subject)
.addFormDataPart("text", text);

html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart(
"html", htmlContent));

for (Attachment attachment : attachments) {
multipartBuilder.addFormDataPart("attachment", attachment
.getFilename(), RequestBody.create(MediaType
.parse(attachment.getContentType()), StreamUtils
.copyToByteArray(attachment.getSource()
.getInputStream())));
}
return multipartBuilder.build();
}
}

@Override
public void send(String to, String subject, String text,
Optional<String> html, Attachment... attachment) {

String apiKey = configurationManager
.getRequiredValue(ConfigurationKeys.MAILGUN_KEY);
String domain = configurationManager
.getRequiredValue(ConfigurationKeys.MAILGUN_DOMAIN);

try {

RequestBody formBody = prepareBody(to, subject, text, html,
attachment);

Request request = new Request.Builder()
.url("https://api.mailgun.net/v2/" + domain + "/messages")
.header("Authorization", Credentials.basic("api", apiKey))
.post(formBody).build();

Response resp = client.newCall(request).execute();
if (!resp.isSuccessful()) {
log.warn("sending email was not successful:" + resp);
}
} catch (IOException e) {
log.warn("error while sending email", e);
}
}
}
Loading

0 comments on commit 0bd9bf4

Please sign in to comment.