List of usage examples for javax.mail Message setHeader
public void setHeader(String header_name, String header_value) throws MessagingException;
From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java
private void sendHTML(final String message) throws MessagingException, IOException { if (message == null || message.isEmpty()) { throw new IllegalArgumentException("message"); }/*from ww w .ja va 2 s . c o m*/ final String host = properties.getConfigString("host"); final Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); final String port = properties.getConfigString("port", null); if (port != null) { props.setProperty("mail.smtp.port", port); } if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) { props.setProperty("mail.smtp.ssl.enable", "true"); } final Session session = Session.getInstance(props, null); // session.setDebug( true ); final javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(properties.getConfigString("from"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(properties.getConfigString("to"), false)); msg.setSubject("superpipes error message"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html"))); msg.setHeader("X-Mailer", "superpipes"); Transport t = null; try { t = session.getTransport("smtp"); final String username = properties.getConfigString("username", null); final String password = properties.getConfigString("password", null); if (username == null || password == null) { t.connect(); } else { if (port == null || port.isEmpty()) { t.connect(host, username, password); } else { t.connect(host, Integer.parseInt(port), username, password); } } t.sendMessage(msg, msg.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w ww.j a v a 2 s . c o m*/ String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w w w . j a v a 2 s . c o m*/ String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:io.kodokojo.service.SmtpEmailSender.java
@Override public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content, boolean htmlContent) { if (CollectionUtils.isEmpty(to)) { throw new IllegalArgumentException("to must be defined."); }/*from w ww . jav a 2 s . co m*/ if (isBlank(content)) { throw new IllegalArgumentException("content must be defined."); } Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); try { message.setFrom(from); message.setSubject(subject); InternetAddress[] toInternetAddress = convertToInternetAddress(to); message.setRecipients(Message.RecipientType.TO, toInternetAddress); if (CollectionUtils.isNotEmpty(cc)) { InternetAddress[] ccInternetAddress = convertToInternetAddress(cc); message.setRecipients(Message.RecipientType.CC, ccInternetAddress); } if (CollectionUtils.isNotEmpty(ci)) { InternetAddress[] ciInternetAddress = convertToInternetAddress(ci); message.setRecipients(Message.RecipientType.BCC, ciInternetAddress); } if (htmlContent) { message.setContent(content, "text/html"); } else { message.setText(content); } message.setHeader("X-Mailer", "Kodo Kojo mailer"); message.setSentDate(new Date()); Transport.send(message); } catch (MessagingException e) { LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e); } }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName, String destination, String destinationCc, String destinationBCc, String contactPerson, String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject, String comment, String replyToAddresses) throws Exception { // Send an e-mail... // create some properties and get the default Session String protocol = "smtp"; if (meta.isUsingAuthentication()) { if (meta.getSecureConnectionType().equals("TLS")) { // Allow TLS authentication data.props.put("mail.smtp.starttls.enable", "true"); } else {/*from ww w .j a v a 2 s. c o m*/ protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown data.props.put("mail.smtps.quitwait", "false"); } } data.props.put("mail." + protocol + ".host", server); if (!Const.isEmpty(port)) data.props.put("mail." + protocol + ".port", port); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) data.props.put("mail.debug", "true"); if (meta.isUsingAuthentication()) data.props.put("mail." + protocol + ".auth", "true"); Session session = Session.getInstance(data.props); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set message priority if (meta.isUsePriority()) { String priority_int = "1"; if (meta.getPriority().equals("low")) priority_int = "3"; if (meta.getPriority().equals("normal")) priority_int = "2"; msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low. msg.setHeader("Importance", meta.getImportance()); //seems to be needed for MS Outlook. //where it returns a string of high /normal /low. } // set Email sender String email_address = senderAddress; if (!Const.isEmpty(email_address)) { // get sender name if (!Const.isEmpty(senderName)) email_address = senderName + '<' + email_address + '>'; msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled")); } // Set reply to if (!Const.isEmpty(replyToAddresses)) { // get replay to // Split the mail-address: space separated String[] reply_Address_List = replyToAddresses.split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); // To add the real reply-to msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = destination.split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); String realdestinationCc = destinationCc; if (!Const.isEmpty(realdestinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = realdestinationCc.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } String realdestinationBCc = destinationBCc; if (!Const.isEmpty(realdestinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = realdestinationBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } if (mailsubject != null) msg.setSubject(mailsubject); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) messageText.append(comment).append(Const.CR).append(Const.CR); if (meta.getIncludeDate()) messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) { messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson) .append(Const.CR); messageText.append(Messages.getString("Mail.Log.Comment.Tel") + " : ").append(contactPhone) .append(Const.CR); messageText.append(Const.CR); } data.parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (meta.isUseHTML()) { if (!Const.isEmpty(meta.getEncoding())) part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding()); else part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } else part1.setText(messageText.toString()); data.parts.addBodyPart(part1); // attached files if (meta.isDynamicFilename()) setAttachedFilesList(r, log); else setAttachedFilesList(null, log); msg.setContent(data.parts); Transport transport = null; try { transport = session.getTransport(protocol); if (meta.isUsingAuthentication()) { if (!Const.isEmpty(port)) { transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } else { transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, "")); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } }
From source file:com.funambol.email.items.manager.PopEntityManager.java
/** * This method creates an email with only header to save in * the local DB.//from www . j ava 2s . c o m * * @param session Mail Server session * @param msg complete message * @return msgForDB Message with only header * @throws EntityException */ private Message createMessageForDB(Message msg, String from, String firstname, String lastname) throws EntityException { Message msgForDB = null; try { // save old Message-ID String mid = Utility.getHeaderMessageID(msg); msgForDB = new MimeMessage(this.pmsw.getSession()); // header MessageCreator.setNewHeaderSent(msgForDB, msg, from, firstname, lastname); // default empty content msgForDB.setContent(Def.CONTENT_BODY, Def.CONTENT_CONTENTTYPE); msgForDB.saveChanges(); // the save message command change the message-ID msgForDB.setHeader(Def.HEADER_MESSAGE_ID, mid); } catch (MessagingException me) { throw new EntityException(me); } return msgForDB; }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
@Override public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body, List<NodeRef> attachments, boolean html) throws Exception { EmailConfig config = getConfig();//from ww w . j av a 2s.c o m EmailProvider provider = getEmailProvider(config.getProviderId()); Properties props = System.getProperties(); String prefix = "mail." + provider.getOutgoingProto() + "."; props.put(prefix + "host", provider.getOutgoingServer()); props.put(prefix + "port", provider.getOutgoingPort()); props.put(prefix + "auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName())); if (to != null) { InternetAddress[] recipients = new InternetAddress[to.size()]; for (int i = 0; i < to.size(); i++) recipients[i] = new InternetAddress(to.get(i)); msg.setRecipients(Message.RecipientType.TO, recipients); } if (cc != null) { InternetAddress[] recipients = new InternetAddress[cc.size()]; for (int i = 0; i < cc.size(); i++) recipients[i] = new InternetAddress(cc.get(i)); msg.setRecipients(Message.RecipientType.CC, recipients); } if (bcc != null) { InternetAddress[] recipients = new InternetAddress[bcc.size()]; for (int i = 0; i < bcc.size(); i++) recipients[i] = new InternetAddress(bcc.get(i)); msg.setRecipients(Message.RecipientType.BCC, recipients); } msg.setSubject(subject); msg.setHeader("X-Mailer", "Alvex Emailer"); msg.setSentDate(new Date()); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); if (body != null) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body, "utf-8", html ? "html" : "plain"); multipart.addBodyPart(messageBodyPart); } if (attachments != null) for (NodeRef att : attachments) { messageBodyPart = new MimeBodyPart(); String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME); messageBodyPart .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService))); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto()); t.connect(config.getUsername(), config.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????//from ww w .jav a2s . c o m * @param toAddressStr * ?To * @param ccAddressStr * ?Cc * @param subject * ?? * @param content * * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ?? return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc//from w w w. ja v a 2 s . c o m */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.clustercontrol.notify.util.SendMail.java
public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ??//from w w w .j av a2s . com return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } // BCC if (bccAddressStr != null) { InternetAddress[] bccAddress = this.getAddress(bccAddressStr); if (bccAddress != null && bccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } if (bccAddressStr != null) { message += ", BCC=" + Arrays.asList(bccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }