public boolean sendTextMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } try { Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator)); mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress())); mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress())); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); mailMessage.setText(mailInfo.getContent()); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); return false; } }
/** * Get the content of a mail message. * * @param message * the mail message * @return the content of the mail message */ private String getMessageContent(Message message) throws MessagingException { try { Object content = message.getContent(); if (content instanceof Multipart) { StringBuffer messageContent = new StringBuffer(); Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { Part part = multipart.getBodyPart(i); if (part.isMimeType("text/plain")) { messageContent.append(part.getContent().toString()); } } return messageContent.toString(); } return content.toString(); } catch (IOException e) { e.printStackTrace(); } return ""; }
@Override public void sendEmail(String address, String subject, String content, Map<String, String> headers) throws Exception { Session session = MailUtilities.makeSession(); if (session == null) { // LogService.getRoot().warning("Unable to create mail session. Not sending mail to "+address+"."); LogService.getRoot().log(Level.WARNING, "com.rapidminer.tools.MailSenderSMTP.creating_mail_session_error", address); } MimeMessage msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, address); msg.setFrom(); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setText(content, "UTF-8"); if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { msg.setHeader(header.getKey(), header.getValue()); } } Transport.send(msg); }
public void send(String addresses, String topic, String textMessage) { try { session.getProperties().put("mail.smtp.port", 25000); Message message = new MimeMessage(session); message.setRecipients(TO, InternetAddress.parse(addresses)); message.setSubject(topic); message.setText(textMessage); Transport.send(message); logger.info("sent mail with resource!"); } catch (MessagingException e) { logger.log(WARNING, "Cannot send mail", e); } }
/** * Sends an email. * * @param from * The Email-address from the sender of this mail. * @param to * The Email-address of the receiver of this mail. * @param subject * The subject of the mail. * @param body * The content of the mail. * @throws MailSendingException * When sending the mail failed. */ public void sendMail(final String from, final String to, final String subject, final String body) throws MailSendingException { final MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSentDate(new Date()); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (final MessagingException e) { throw new MailSendingException("Sending an email failed.", e); } }
private SearchTerm createFieldSearchTerm(String f) { switch (f.toLowerCase()) { case "from": return new FromStringTerm(matchingText); case "cc": return new RecipientStringTerm(Message.RecipientType.CC, matchingText); case "to": return new RecipientStringTerm(Message.RecipientType.TO, matchingText); case "body": return new BodyTerm(matchingText); case "subject": return new SubjectTerm(matchingText); default: return null; } }
private void moveMessage(Message toMove, Folder dest) { if (toMove != null) { try { final Folder source = toMove.getFolder(); final Message[] messages = new Message[]{toMove}; source.setFlags(messages, FLAGS_DELETED, true); source.copyMessages(messages, dest); moveCount++; } catch (MessagingException ex) { throw new RuntimeException(ex); } } }
private void prepareAndSendMail(final SimpleUserOrg user, final String password) { sendMail(mimeMessage -> { final String fullName = user.getFirstName() + " " + user.getLastName(); final InternetAddress[] internetAddresses = getUserInternetAdresses(user, fullName); final String link = "<a href=\"" + configurationResource.get(URL_PUBLIC) + "\">" + configurationResource.get(URL_PUBLIC) + "</a>"; mimeMessage.setHeader("Content-Type", "text/plain; charset=UTF-8"); mimeMessage.setFrom(new InternetAddress(configurationResource.get(MESSAGE_FROM), configurationResource.get(MESSAGE_FROM_TITLE), StandardCharsets.UTF_8.name())); mimeMessage.setSubject(String.format(configurationResource.get(MESSAGE_NEW_SUBJECT), fullName), StandardCharsets.UTF_8.name()); mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); mimeMessage.setContent(String.format(configurationResource.get(MESSAGE_NEW), fullName, user.getId(), password, link, fullName, user.getId(), password, link), "text/html; charset=UTF-8"); }); }
/** * Extracts string data from {@link MimeMessage}. * * @param mimeMessage * @return */ public static String getStringInfo(MimeMessage mimeMessage) { StringBuilder sb = new StringBuilder("MimeMessage: "); try { sb.append("from=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getFrom())).append("; "); sb.append("replyTo=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getReplyTo())).append("; "); sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.TO))).append("; "); sb.append("cc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.CC))).append("; "); sb.append("bcc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.BCC))).append("; "); sb.append("subject=").append(mimeMessage.getSubject()); } catch (MessagingException e) { LOG.error("Error retrieving log message: {}", e.getMessage()); } return sb.toString(); }
@Test public void sendReport() throws MessagingException { mockStatic(Transport.class); expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator); expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost"); expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25"); expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" }); expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]); expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]); expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom"); Transport.send(isA(Message.class)); replayAll(); triggerRun(); verifyAll(); }
public static void sendMail(String host, int port, String username, String password, String recipients, String subject, String content, String from) throws AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); message.setSubject(subject); message.setText(content); Transport.send(message); }
@Override public void sendMessage(Message msg, Address[] addresses) throws MessagingException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { msg.writeTo(out); lastMail = new String(out.toByteArray(), "UTF-8"); } catch (IOException ex) { throw new RuntimeException(ex); } }
private static void sendMail() throws MessagingException, IOException { Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( getVal("username"), getVal("password")); } }); session.setDebug(getBoolVal("mail.debug")); LOG.info("Compiling Mail before Sending"); Message message = createMessage(session); Transport transport = session.getTransport("smtp"); LOG.info("Connecting to Mail Server"); transport.connect(); LOG.info("Sending Mail"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); LOG.info("Reports are sent to Mail"); clearTempZips(); }
/** * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】 */ public boolean isNew() throws MessagingException { boolean isnew = false; Flags flags = ((Message) mimeMessage).getFlags(); Flags.Flag[] flag = flags.getSystemFlags(); logger.info("flags's length: " + flag.length); for (int i = 0; i < flag.length; i++) { if (flag[i] == Flags.Flag.SEEN) { isnew = true; logger.info("seen Message......."); break; } } return isnew; }
public static String sendCode(User user, HttpServletRequest request) { try { Session session = EmailActions.authorizeWebShopEmail(); String code = Long.toHexString(Double.doubleToLongBits(Math.random())); request.getSession().setAttribute("deleteAccountCode", code); request.getSession().setAttribute("userName", user.getLogin()); System.out.println(code); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.geteMail(), false)); msg.setSubject("Delete account"); msg.setText("Link : " + ApplicationProperties.URL + ApplicationProperties.PROJECT_NAME + "account/deleteAccountCode/" + code); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { System.out.println("Error : " + e); } return "loginAndRegistration/reset/codePassword"; }
public static void sendMail(String subject, String content, String receivers, String path){ recipients = receivers; new EmailUtil(); Message message; try { String suffix = new File(path).getName(); if(suffix.endsWith(".jpg") || suffix.endsWith(".png") || suffix.endsWith(".gif")){ message = createImageMail(subject, content, path); }else{ message = createAttachMail(subject, content, path); } ts.sendMessage(message, message.getAllRecipients()); ts.close(); System.out.println("send email finished."); } catch (Exception e) { System.err.println("send email failed."); e.printStackTrace(); } }
public boolean sendAttachMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } try { Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator)); mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress())); mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress())); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart multi = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); multi.addBodyPart(textBodyPart); for (String path : mailInfo.getAttachFileNames()) { DataSource fds = new FileDataSource(path); BodyPart fileBodyPart = new MimeBodyPart(); fileBodyPart.setDataHandler(new DataHandler(fds)); fileBodyPart.setFileName(path.substring(path.lastIndexOf("/") + 1)); multi.addBodyPart(fileBodyPart); } mailMessage.setContent(multi); mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); return false; } }
public boolean sendHtmlMail(MailSenderInfo mailInfo) { XLog.d("发送网页版邮件!"); MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } try { Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator)); mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress())); String[] receivers = mailInfo.getReceivers(); Address[] tos = new InternetAddress[receivers.length]; for (int i = 0; i < receivers.length; i++) { tos[i] = new InternetAddress(receivers[i]); } mailMessage.setRecipients(Message.RecipientType.TO, tos); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); mailMessage.setContent(mainPart); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); return false; } }
/** * @Method: createImageMail * @Description: ����һ���ʼ����Ĵ�ͼƬ���ʼ� * @param session * @return * @throws Exception */ public static MimeMessage createImageMail(String subject, String content, String imagePath) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); if(recipients.contains(";")){ List<InternetAddress> list = new ArrayList<InternetAddress>(); String []median=recipients.split(";"); for(int i=0;i<median.length;i++){ list.add(new InternetAddress(median[i])); } InternetAddress[] address =list.toArray(new InternetAddress[list.size()]); message.setRecipients(Message.RecipientType.TO,address); }else{ message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); } message.setSubject(subject); MimeBodyPart text = new MimeBodyPart(); text.setContent(content, "text/html;charset=UTF-8"); MimeBodyPart image = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource(imagePath)); image.setDataHandler(dh); image.setContentID("xxx.jpg"); MimeMultipart mm = new MimeMultipart(); mm.addBodyPart(text); mm.addBodyPart(image); mm.setSubType("related"); message.setContent(mm); message.saveChanges(); return message; }
/** * 设置收信人 * * @param to * @return */ public boolean setTo(String to) { if (to == null) return false; logger.info(Resources.getMessage("EMAIL.SET_TO"), to); try { mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); return true; } catch (Exception e) { logger.error(e.getLocalizedMessage()); return false; } }
/** * 设置抄送人 * @param copyto * @return */ public boolean setCopyTo(String copyto) { if (copyto == null) return false; logger.info(Resources.getMessage("EMAIL.SET_COPYTO"), copyto); try { mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto)); return true; } catch (Exception e) { return false; } }
/** * 发送邮件 * * @param name String * @param pass String */ public boolean sendout() { try { mimeMsg.setContent(mp); mimeMsg.saveChanges(); logger.info(Resources.getMessage("EMAIL.SENDING")); Session mailSession = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { if (userkey == null || "".equals(userkey.trim())) { return null; } return new PasswordAuthentication(username, userkey); } }); Transport transport = mailSession.getTransport("smtp"); transport.connect((String) props.get("mail.smtp.host"), username, password); // 设置发送日期 mimeMsg.setSentDate(new Date()); // 发送 transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) { transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC)); } logger.info(Resources.getMessage("EMAIL.SEND_SUCC")); transport.close(); return true; } catch (Exception e) { logger.error(Resources.getMessage("EMAIL.SEND_ERR"), e); return false; } }
private MailCopier() { pManager = PManager.getInstance(); files = new LinkedList<File>(); filesStr = new LinkedList<String>(); messages = new LinkedList<Message>(); messagesStr = new LinkedList<String>(); fPointer = 0; mPointer = 0; attach_part = null; copierListeners = new LinkedList<CopierListener>(); Security.addProvider(new Provider()); }
public void sendMultipartMessage(String subject, String[] to, String text, String attach) throws MessagingException, IOException { MimeMessage message = new MimeMessage(senderSession); message.setFrom(new InternetAddress(pManager.get_SENDER_From())); // FROM for(int i=0; i < to.length; i++) { if(!to[i].equals("")) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); // TO } } message.setSubject(subject); //SUBJECT Multipart mp = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setText(text); mp.addBodyPart(textPart); // TEXT MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(attach); mp.addBodyPart(attachPart); // ATTACH message.setContent(mp); transport.sendMessage(message, message.getAllRecipients()); }
/** * 發送單條email * * @param emailInfo */ public void send(final EmailInfo emailInfo) { this.theadPool.execute(new Runnable() { public void run() { EmailContext emailContext = new EmailContext(); emailContext.setEmailInfo(emailInfo); try { Message msg = buildEmailMessage(emailInfo); Transport.send(msg); } catch (Exception e) { emailContext.setThrowable(e); } } }); }
private Message buildEmailMessage(EmailInfo emailInfo) throws AddressException, MessagingException, UnsupportedEncodingException { MimeMessage message = new MimeMessage(this.session); message.setFrom(new InternetAddress(emailInfo.getFrom(), "网页更新订阅系统", "UTF-8")); message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailInfo.getTo())); Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailInfo.getContent(), "text/html;charset=UTF-8"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setSubject(emailInfo.getTitle()); message.saveChanges(); return message; }
/** * Send a message, using the borrowed {@link Transport}. */ @Override public void sendMessage(Message message, Address[] addresses) throws MessagingException { if (wrapped == null) { throw new IllegalStateException ("Not connected!"); } wrapped.sendMessage(message, addresses); }
public void sendMail(int uID, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd, DB dbProperties) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", mailserver); props.put("mail.smtp.port", mailport); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailuser, mailpass); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(mailsendadd)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(ForgotDao.getEmail(uID, dbProperties))); message.setSubject("Forgot your password!"); message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to gain access to your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8"); Transport.send(message); System.out.println("Forgot Password E-mail Sent - "+ForgotDao.getEmail(uID, dbProperties)); } catch (MessagingException e) { System.out.println("Error - Forgot Password E-mail Send FAILED - "+ForgotDao.getEmail(uID, dbProperties)); throw new RuntimeException(e); } }
/** * 设置抄送人 * * @param name String * @param pass String */ public boolean setCopyTo(String copyto) { if (copyto == null) return false; logger.info(Resources.getMessage("EMAIL.SET_COPYTO"), copyto); try { mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto)); return true; } catch (Exception e) { return false; } }
public static void sendEmail(EmailSettingContent emailSetting, String acceptor, String subject, String body) { Properties props = buildProperty(emailSetting); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String username = null; String password = null; if (emailSetting.isAuthenticated()) { username = emailSetting.getUsername(); password = emailSetting.getPassword(); } return new PasswordAuthentication(username, password); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailSetting.getSender())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(acceptor)); message.setSubject(subject, "utf8"); message.setContent(body, "text/html;charset=utf8"); Transport.send(message); } catch (Throwable throwable) { } }
@Override public boolean matches(Message m, List<_BridgeMessageContent> contents) throws MessagingException { String[] headers = m.getHeader("User-Agent"); if (headers != null) { for (String header : headers) { if (StringUtils.containsIgnoreCase(header, getId())) { return true; } } } return false; }
public List<MetaData> getAllMetaData() throws RbvException { //first check if the folder is open if (!isOpen) { throw new MatchableNotOpenException(getDescription() + " is not open"); } try { allMetaDataList.clear(); newMetaDataList.clear(); boolean hasNew = folder.hasNewMessages(); log.debug("Has new messages in folder: " + hasNew); Message[] imapMessages = folder.getMessages(); for (Message imapMessage : imapMessages) { ImapMetaData currentMeta = createImapMetaData((MimeMessage) imapMessage); if (currentMeta != null) { if (!imapMessage.getFlags().contains(Flags.Flag.FLAGGED)) { newMetaDataList.add(currentMeta); } imapMessage.setFlag(Flags.Flag.FLAGGED, true); allMetaDataList.add(currentMeta); } } //this was the first pass isInitialPass = false; return allMetaDataList; } catch (MessagingException me) { throw new RbvStorageException("Could not get meta data from " + getDescription(), me); } }
/** * Not a public method returning all available messages in the form of java mail message * * @return * @throws RbvException */ Message[] getAllMimeMessages() throws RbvException { //first check if the folder is open if (!isOpen) { throw new MatchableNotOpenException(getDescription() + " is not open"); } try { return folder.getMessages(); } catch (MessagingException me) { throw new RbvStorageException("Could not get meta data from " + getDescription(), me); } }
public static void sendEmailWithOrder(String text, String eMail, HttpServletRequest request) { try { Session session = EmailActions.authorizeWebShopEmail(); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMail, false)); msg.setSubject("Shop order"); msg.setText(text); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { System.out.println("Error : " + e); } }
/** * Get the content of the last message with the given subject. * * @param subject * the subject * @return the content of the last message with the given subject */ public String getLastMailContentWithSubject(String subject) throws MessagingException { // Download message headers from server. int retries = 0; String content = null; while (retries < 40) { // Open main "INBOX" folder. Folder folder = getStore().getFolder(MAIL_INBOX); folder.open(Folder.READ_WRITE); // Get folder's list of messages. Message[] messages = folder.getMessages(); // Retrieve message headers for each message in folder. FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); folder.fetch(messages, profile); for (Message message : messages) { if (message.getSubject().equals(subject)) { content = getMessageContent(message); } } folder.close(true); if (content != null) { return content; } try { Thread.sleep(1000); } catch (InterruptedException e) { // ignored } retries++; } return ""; }