Search in sources :

Example 1 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project remusic by aa112901.

the class CommonUtils method sendTextMail.

/**
     * 以文本格式发送邮件
     * @param title 待发送的邮件的信息
     */
public static boolean sendTextMail(String title, String content) {
    try {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", "smtp.163.com");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props, null);
        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.163.com", 25, "remusic_log@163.com", "remusiclog1");
        Message mailMessage = new SMTPMessage(session);
        Address from = new InternetAddress("remusic_log@163.com");
        mailMessage.setFrom(from);
        Address to = new InternetAddress("remusic_log@163.com");
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        mailMessage.setSubject(title);
        mailMessage.setSentDate(new Date());
        mailMessage.setText(content);
        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) SMTPMessage(com.sun.mail.smtp.SMTPMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Transport(javax.mail.Transport) Date(java.util.Date) Session(javax.mail.Session)

Example 2 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project zm-mailbox by Zimbra.

the class AutoProvision method sendNotifMessage.

protected void sendNotifMessage(Account acct, String password) throws ServiceException {
    String subject = fillTemplate(acct, domain.getAutoProvNotificationSubject());
    String body = fillTemplate(acct, domain.getAutoProvNotificationBody());
    String from = domain.getAutoProvNotificationFromAddress();
    if (from == null) {
        // TODO: should we use a seperate boolean control?
        return;
    }
    String toAddr = acct.getName();
    try {
        SMTPMessage out = new SMTPMessage(JMSession.getSmtpSession());
        InternetAddress addr = null;
        try {
            addr = new JavaMailInternetAddress(from);
        } catch (AddressException e) {
            // log and try the next one
            ZimbraLog.autoprov.warn("invalid address in " + Provisioning.A_zimbraAutoProvNotificationFromAddress, e);
        }
        Address fromAddr = addr;
        Address replyToAddr = addr;
        // From
        out.setFrom(fromAddr);
        // Reply-To
        out.setReplyTo(new Address[] { replyToAddr });
        // To
        out.setRecipient(javax.mail.Message.RecipientType.TO, new JavaMailInternetAddress(toAddr));
        // Date
        out.setSentDate(new Date());
        // Subject
        Locale locale = acct.getLocale();
        out.setSubject(subject);
        // NOTIFY=NEVER
        out.setNotifyOptions(SMTPMessage.NOTIFY_NEVER);
        // body
        MimeMultipart mmp = new ZMimeMultipart("alternative");
        // TEXT part (add me first!)
        String text = body;
        MimeBodyPart textPart = new ZMimeBodyPart();
        textPart.setText(text, MimeConstants.P_CHARSET_UTF8);
        mmp.addBodyPart(textPart);
        // HTML part
        StringBuilder html = new StringBuilder();
        html.append("<h4>\n");
        html.append("<p>" + body + "</p>\n");
        html.append("</h4>\n");
        html.append("\n");
        MimeBodyPart htmlPart = new ZMimeBodyPart();
        htmlPart.setDataHandler(new DataHandler(new HtmlPartDataSource(html.toString())));
        mmp.addBodyPart(htmlPart);
        out.setContent(mmp);
        // send it
        Transport.send(out);
        // log
        Address[] rcpts = out.getRecipients(javax.mail.Message.RecipientType.TO);
        StringBuilder rcptAddr = new StringBuilder();
        for (Address a : rcpts) rcptAddr.append(a.toString());
        ZimbraLog.autoprov.info("auto provision notification sent rcpt='" + rcptAddr + "' Message-ID=" + out.getMessageID());
    } catch (MessagingException e) {
        ZimbraLog.autoprov.warn("send auto provision notification failed rcpt='" + toAddr + "'", e);
    }
}
Also used : Locale(java.util.Locale) SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) Address(javax.mail.Address) EmailAddress(com.zimbra.cs.account.names.NameUtil.EmailAddress) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 3 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage 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);
}
Also used : Locale(java.util.Locale) Account(com.zimbra.cs.account.Account) SMTPMessage(com.sun.mail.smtp.SMTPMessage) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) MessagingException(javax.mail.MessagingException) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MailSender(com.zimbra.cs.mailbox.MailSender) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 4 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage in project zm-mailbox by Zimbra.

the class SmtpTransport method sendMessage.

/**
     * Sends the message to the recipients. This implementation immediately
     * closes the SMTP connection after sending a message, which might be
     * incompatible with JavaMail.
     *
     * @param msg message to send
     * @param rcpts recipients, may be different from ones in the MIME header
     */
@Override
public void sendMessage(Message msg, Address[] rcpts) throws MessagingException {
    Preconditions.checkArgument(msg instanceof MimeMessage);
    Preconditions.checkState(connection != null);
    String sender = session.getProperty("mail." + protocol + ".from");
    if (msg instanceof SMTPMessage) {
        SMTPMessage smtpMsg = (SMTPMessage) msg;
        if (smtpMsg.getEnvelopeFrom() != null) {
            sender = smtpMsg.getEnvelopeFrom();
        }
    }
    try {
        if (sender != null) {
            connection.sendMessage(sender, rcpts, (MimeMessage) msg);
        } else {
            connection.sendMessage(rcpts, (MimeMessage) msg);
        }
    } catch (MessagingException e) {
        ZimbraLog.smtp.warn("Failed to send message", e);
        notify(e, msg, rcpts);
    } catch (IOException e) {
        ZimbraLog.smtp.warn("Failed to send message", e);
        notify(e, msg, rcpts);
    }
    notify(null, msg, rcpts);
}
Also used : SMTPMessage(com.sun.mail.smtp.SMTPMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 5 with SMTPMessage

use of com.sun.mail.smtp.SMTPMessage 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);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) SMTPMessage(com.sun.mail.smtp.SMTPMessage) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) Date(java.util.Date) DbConnection(com.zimbra.cs.db.DbPool.DbConnection)

Aggregations

SMTPMessage (com.sun.mail.smtp.SMTPMessage)12 MessagingException (javax.mail.MessagingException)8 InternetAddress (javax.mail.internet.InternetAddress)8 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)6 Date (java.util.Date)6 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)5 MimeBodyPart (javax.mail.internet.MimeBodyPart)5 MimeMessage (javax.mail.internet.MimeMessage)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 Account (com.zimbra.cs.account.Account)3 Locale (java.util.Locale)3 Address (javax.mail.Address)3 Session (javax.mail.Session)3 IOException (java.io.IOException)2 DataHandler (javax.activation.DataHandler)2 Transport (javax.mail.Transport)2 AddressException (javax.mail.internet.AddressException)2 ServiceException (com.zimbra.common.service.ServiceException)1 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)1