use of javax.mail.internet.InternetAddress in project zm-mailbox by Zimbra.
the class FilterUtil method reject.
public static void reject(OperationContext octxt, Mailbox mailbox, ParsedMessage parsedMessage, String reason, LmtpEnvelope envelope) throws MessagingException, ServiceException {
MimeMessage mimeMessage = parsedMessage.getMimeMessage();
if (isMailLoop(mailbox, mimeMessage, new String[] { HEADER_FORWARDED })) {
// Detected a mail loop. Do not send MDN, but just discard the message
String error = String.format("Detected a mail loop for message %s. No MDN sent.", Mime.getMessageID(mimeMessage));
ZimbraLog.filter.info(error);
throw ServiceException.FAILURE(error, null);
}
String reportTo = null;
if (envelope != null && envelope.hasSender()) {
reportTo = envelope.getSender().getEmailAddress();
}
if (reportTo == null || reportTo.isEmpty()) {
String[] returnPath = mimeMessage.getHeader(HEADER_RETURN_PATH);
if (returnPath == null || returnPath.length == 0) {
// >> NOT be generated if the MAIL FROM (or Return-Path) is empty.
throw new MessagingException("Neither 'envelope from' nor 'Return-Path' specified. Can't locate the address to reject to (No MDN sent)");
} else {
// At least one 'return-path' should exist.
reportTo = returnPath[0];
}
}
Account owner = mailbox.getAccount();
Locale locale = owner.getLocale();
String charset = owner.getPrefMailDefaultCharset();
if (charset == null) {
charset = MimeConstants.P_CHARSET_UTF8;
}
SMTPMessage report = new SMTPMessage(JMSession.getSmtpSession());
// add the forwarded header account names to detect the mail loop between accounts
for (String headerFwdAccountName : Mime.getHeaders(mimeMessage, HEADER_FORWARDED)) {
report.addHeader(HEADER_FORWARDED, headerFwdAccountName);
}
report.addHeader(HEADER_FORWARDED, owner.getName());
// MDN header
report.setEnvelopeFrom("<>");
report.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(reportTo));
String subject = L10nUtil.getMessage(MsgKey.seiveRejectMDNSubject, locale);
report.setSubject(subject);
report.setSentDate(new Date());
InternetAddress address = new JavaMailInternetAddress(owner.getName());
report.setFrom(address);
MimeMultipart multi = new ZMimeMultipart("report");
// part 1: human-readable notification
String text = L10nUtil.getMessage(MsgKey.seiveRejectMDNErrorMsg, locale) + "\n" + reason;
MimeBodyPart mpText = new ZMimeBodyPart();
mpText.setText(text, CharsetUtil.checkCharset(text, charset));
multi.addBodyPart(mpText);
// part 2: disposition notification
StringBuilder mdn = new StringBuilder();
mdn.append("Final-Recipient: rfc822;").append(owner.getName()).append("\r\n");
mdn.append("Disposition: automatic-action/MDN-sent-automatically");
mdn.append("; deleted\r\n");
MimeBodyPart mpMDN = new ZMimeBodyPart();
mpMDN.setText(mdn.toString(), MimeConstants.P_CHARSET_UTF8);
mpMDN.setHeader("Content-Type", "message/disposition-notification; charset=utf-8");
multi.addBodyPart(mpMDN);
// Assemble the MDN
report.setContent(multi);
report.setHeader("Content-Type", multi.getContentType() + "; report-type=disposition-notification");
report.saveChanges();
MailSender mailSender = mailbox.getMailSender().setSaveToSent(false);
mailSender.setRecipients(reportTo);
mailSender.setEnvelopeFrom("<>");
mailSender.sendMimeMessage(octxt, mailbox, report);
}
use of javax.mail.internet.InternetAddress in project zm-mailbox by Zimbra.
the class BounceMsg method addResentRecipientHeader.
/** Adds a new header to the {@link MimeMessage} consisting of the given
* the {@link InternetAddress}es. (Note that this is an add and not a
* set, as you can have multiple sets of {@code Resent-*} headers on a
* message if the message has been resent repeatedly.)
* @param mm The message to add headers to.
* @param name The name of the header being added.
* @param addrs The addrs being serialized to the header.
* @return a non-{@code null} {@code List} of the email parts of the added
* addresses. */
List<String> addResentRecipientHeader(MimeMessage mm, String name, InternetAddress[] addrs) throws MessagingException {
if (addrs == null || addrs.length == 0)
return Collections.emptyList();
mm.addHeader(name, Joiner.on(", ").join(addrs));
List<String> recipients = new ArrayList<String>(5);
for (InternetAddress addr : addrs) {
recipients.add(addr.getAddress());
}
return recipients;
}
use of javax.mail.internet.InternetAddress in project zm-mailbox by Zimbra.
the class TestSmtpClient method testMimeMessage.
@Test
public void testMimeMessage() throws Exception {
TestUtil.createAccount(USER_NAME);
TestUtil.createAccount(USER2_NAME);
// Assemble the message.
MimeMessage mm = new ZMimeMessage(JMSession.getSession());
InternetAddress addr = new JavaMailInternetAddress(TestUtil.getAddress(USER_NAME));
mm.setFrom(addr);
mm.setRecipient(RecipientType.TO, addr);
String subject = NAME_PREFIX + " testMimeMessage";
mm.setSubject(subject);
mm.setText("testMimeMessage");
mm.saveChanges();
// Initialize SMTP client.
SmtpConfig config = new SmtpConfig(mHost, mPort, "localhost");
SmtpConnection conn = new SmtpConnection(config);
conn.sendMessage(mm);
// Make sure it arrived.
ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
TestUtil.waitForMessage(mbox, "in:inbox subject:\"" + subject + "\"");
// Send the same message to a different envelope recipient.
conn.sendMessage(addr.getAddress(), new String[] { TestUtil.getAddress(USER2_NAME) }, mm);
mbox = TestUtil.getZMailbox(USER2_NAME);
TestUtil.waitForMessage(mbox, "in:inbox subject:\"" + subject + "\"");
}
use of javax.mail.internet.InternetAddress in project zm-mailbox by Zimbra.
the class AppendMessage method store.
private int store(Mailbox mbox, Folder folder) throws ImapSessionClosedException, ServiceException, IOException {
boolean idxAttach = mbox.attachmentsIndexingEnabled();
Long receivedDate = date != null ? date.getTime() : null;
ParsedMessage pm = new ParsedMessage(content, receivedDate, idxAttach);
try {
if (!pm.getSender().isEmpty()) {
InternetAddress ia = new JavaMailInternetAddress(pm.getSender());
if (AccountUtil.addressMatchesAccountOrSendAs(mbox.getAccount(), ia.getAddress())) {
flags |= Flag.BITMASK_FROM_ME;
}
}
} catch (Exception e) {
}
DeliveryOptions dopt = new DeliveryOptions().setFolderId(folder).setNoICal(true).setFlags(flags).setTags(tags);
Message msg = mbox.addMessage(handler.getContext(), pm, dopt, null);
if (msg != null && sflags != 0 && handler.getState() == ImapHandler.State.SELECTED) {
ImapFolder selectedFolder = handler.getSelectedFolder();
// (note that this leaves session flags unset on remote appended messages)
if (selectedFolder != null) {
ImapMessage i4msg = selectedFolder.getById(msg.getId());
if (i4msg != null) {
i4msg.setSessionFlags(sflags, selectedFolder);
}
}
}
return msg == null ? -1 : msg.getId();
}
use of javax.mail.internet.InternetAddress in project zm-mailbox by Zimbra.
the class Notification method outOfOfficeIfNecessary.
/**
* If the recipient's account requires out of office notification,
* send it out. We send these out based on users' setting, and
* the incoming message meeting certain criteria.
*/
private void outOfOfficeIfNecessary(Account account, Mailbox mbox, MimeMessage mm, Integer msgId, String rcpt, String envSenderString) throws ServiceException, MessagingException {
boolean replyEnabled = account.isPrefOutOfOfficeReplyEnabled();
if (ZimbraLog.mailbox.isDebugEnabled()) {
ZimbraLog.mailbox.debug("outofoffice reply enabled=" + replyEnabled + " rcpt='" + rcpt + "' mid=" + msgId);
}
if (!replyEnabled) {
return;
}
// Check if we are in any configured out of office interval
Date now = new Date();
Date fromDate = account.getGeneralizedTimeAttr(Provisioning.A_zimbraPrefOutOfOfficeFromDate, null);
if (fromDate != null && now.before(fromDate)) {
ofailed("from date not reached", null, rcpt, msgId);
return;
}
Date untilDate = account.getGeneralizedTimeAttr(Provisioning.A_zimbraPrefOutOfOfficeUntilDate, null);
if (untilDate != null && now.after(untilDate)) {
ofailed("until date reached", null, rcpt, msgId);
return;
}
// If envelope sender is empty
if (envSenderString == null) {
ofailed("envelope sender null", null, rcpt, msgId);
return;
}
if (envSenderString.length() < 1) {
// be conservative
ofailed("envelope sender empty", null, rcpt, msgId);
return;
}
InternetAddress envSender;
try {
// NB: 'strict' being 'true' causes <> to except
envSender = new JavaMailInternetAddress(envSenderString, true);
} catch (AddressException ae) {
ofailed("envelope sender invalid", envSenderString, rcpt, msgId, ae);
return;
}
String destination = envSender.getAddress();
if (Mime.isAutoSubmitted(mm)) {
ofailed("auto-submitted not no", destination, rcpt, msgId);
return;
}
// If precedence is bulk, junk or list
String[] precedence = mm.getHeader("Precedence");
if (hasPrecedence(precedence, "bulk")) {
ofailed("precedence bulk", destination, rcpt, msgId);
return;
} else if (hasPrecedence(precedence, "junk")) {
ofailed("precedence junk", destination, rcpt, msgId);
return;
} else if (hasPrecedence(precedence, "list")) {
ofailed("precedence list", destination, rcpt, msgId);
return;
}
// Check if the envelope sender indicates a mailing list owner and such
String[] envSenderAddrParts = EmailUtil.getLocalPartAndDomain(destination);
if (envSenderAddrParts == null) {
ofailed("envelope sender invalid", destination, rcpt, msgId);
return;
}
String envSenderLocalPart = envSenderAddrParts[0];
envSenderLocalPart = envSenderLocalPart.toLowerCase();
if (envSenderLocalPart.startsWith("owner-") || envSenderLocalPart.endsWith("-owner")) {
ofailed("envelope sender has owner- or -owner", destination, rcpt, msgId);
return;
}
if (envSenderLocalPart.contains("-request")) {
ofailed("envelope sender contains -request", destination, rcpt, msgId);
return;
}
if (envSenderLocalPart.equals("mailer-daemon")) {
ofailed("envelope sender is mailer-daemon", destination, rcpt, msgId);
return;
}
if (envSenderLocalPart.equals("majordomo")) {
ofailed("envelope sender is majordomo", destination, rcpt, msgId);
return;
}
if (envSenderLocalPart.equals("listserv")) {
ofailed("envelope sender is listserv", destination, rcpt, msgId);
return;
}
// multipart/report is also machine generated
String ct = mm.getContentType();
if (ct != null && ct.equalsIgnoreCase("multipart/report")) {
ofailed("content-type multipart/report", destination, rcpt, msgId);
return;
}
// Check if recipient was directly mentioned in to/cc of this message
String[] otherAccountAddrs = account.getMultiAttr(Provisioning.A_zimbraPrefOutOfOfficeDirectAddress);
if (!AccountUtil.isDirectRecipient(account, otherAccountAddrs, mm, OUT_OF_OFFICE_DIRECT_CHECK_NUM_RECIPIENTS)) {
ofailed("not direct", destination, rcpt, msgId);
return;
}
// If we've already sent to this user, do not send again
DbConnection conn = null;
try {
conn = DbPool.getConnection(mbox);
if (DbOutOfOffice.alreadySent(conn, mbox, destination, account.getTimeInterval(Provisioning.A_zimbraPrefOutOfOfficeCacheDuration, DEFAULT_OUT_OF_OFFICE_CACHE_DURATION_MILLIS))) {
ofailed("already sent", destination, rcpt, msgId);
return;
}
} finally {
DbPool.quietClose(conn);
}
// Send the message
try {
SMTPMessage out = new SMTPMessage(JMSession.getSmtpSession());
// Set From and Reply-To.
out.setFrom(AccountUtil.getFromAddress(account));
InternetAddress replyTo = AccountUtil.getReplyToAddress(account);
if (replyTo != null) {
out.setReplyTo(new Address[] { replyTo });
}
// To
out.setRecipient(javax.mail.Message.RecipientType.TO, envSender);
// Date
out.setSentDate(new Date());
// Subject
String subject = Mime.getSubject(mm);
String replySubjectPrefix = L10nUtil.getMessage(L10nUtil.MsgKey.replySubjectPrefix, account.getLocale());
if (subject == null) {
subject = replySubjectPrefix;
} else if (!subject.toLowerCase().startsWith(replySubjectPrefix.toLowerCase())) {
subject = replySubjectPrefix + " " + subject;
}
String charset = getCharset(account, subject);
out.setSubject(subject, charset);
// In-Reply-To
String messageId = mm.getMessageID();
if (messageId != null && !messageId.trim().equals("")) {
out.setHeader("In-Reply-To", messageId);
}
// Auto-Submitted
out.setHeader("Auto-Submitted", "auto-replied (zimbra; vacation)");
// Precedence (discourage older systems from responding)
out.setHeader("Precedence", "bulk");
// check whether to send "external" OOO reply
if (account.isPrefOutOfOfficeSuppressExternalReply() && isOfExternalSenderType(destination, account, mbox) && !isInternalSender(destination, account)) {
ZimbraLog.mailbox.info(destination + " is external user and no external reply option is set, so no OOO will be sent. ");
return;
}
boolean sendExternalReply = account.isPrefOutOfOfficeExternalReplyEnabled() && !isInternalSender(destination, account) && isOfExternalSenderType(destination, account, mbox);
String body = account.getAttr(sendExternalReply ? Provisioning.A_zimbraPrefOutOfOfficeExternalReply : Provisioning.A_zimbraPrefOutOfOfficeReply, "");
charset = getCharset(account, body);
out.setText(body, charset);
if (Provisioning.getInstance().getConfig().getBooleanAttr(Provisioning.A_zimbraAutoSubmittedNullReturnPath, true)) {
out.setEnvelopeFrom("<>");
} else {
out.setEnvelopeFrom(account.getName());
}
MailSender sender = mbox.getMailSender();
sender.setSaveToSent(false);
sender.setDsnNotifyOptions(MailSender.DsnNotifyOption.NEVER);
sender.sendMimeMessage(null, mbox, out);
ZimbraLog.mailbox.info("outofoffice sent dest='" + destination + "' rcpt='" + rcpt + "' mid=" + msgId);
// Save so we will not send to again
try {
conn = DbPool.getConnection(mbox);
DbOutOfOffice.setSentTime(conn, mbox, destination);
conn.commit();
} finally {
DbPool.quietClose(conn);
}
} catch (MessagingException me) {
ofailed("send failed", destination, rcpt, msgId, me);
}
}
Aggregations