001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.core.net; 018 019 import javax.mail.Message; 020 import javax.mail.MessagingException; 021 import javax.mail.Session; 022 import javax.mail.internet.AddressException; 023 import javax.mail.internet.InternetAddress; 024 import javax.mail.internet.MimeMessage; 025 026 /** 027 * Helper class for SMTPManager. 028 */ 029 public class MimeMessageBuilder { 030 private final MimeMessage message; 031 032 public MimeMessageBuilder(final Session session) { 033 message = new MimeMessage(session); 034 } 035 036 public MimeMessageBuilder setFrom(final String from) throws MessagingException { 037 final InternetAddress address = parseAddress(from); 038 039 if (null != address) { 040 message.setFrom(address); 041 } else { 042 try { 043 message.setFrom(); 044 } catch (final Exception ex) { 045 message.setFrom(null); 046 } 047 } 048 return this; 049 } 050 051 public MimeMessageBuilder setReplyTo(final String replyTo) throws MessagingException { 052 final InternetAddress[] addresses = parseAddresses(replyTo); 053 054 if (null != addresses) { 055 message.setReplyTo(addresses); 056 } 057 return this; 058 } 059 060 public MimeMessageBuilder setRecipients(final Message.RecipientType recipientType, final String recipients) 061 throws MessagingException { 062 final InternetAddress[] addresses = parseAddresses(recipients); 063 064 if (null != addresses) { 065 message.setRecipients(recipientType, addresses); 066 } 067 return this; 068 } 069 070 public MimeMessageBuilder setSubject(final String subject) throws MessagingException { 071 if (subject != null) { 072 message.setSubject(subject, "UTF-8"); 073 } 074 return this; 075 } 076 077 public MimeMessage getMimeMessage() { 078 return message; 079 } 080 081 private static InternetAddress parseAddress(final String address) throws AddressException { 082 return address == null ? null : new InternetAddress(address); 083 } 084 085 private static InternetAddress[] parseAddresses(final String addresses) throws AddressException { 086 return addresses == null ? null : InternetAddress.parse(addresses, true); 087 } 088 }