public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom(); if (froms.length < 1) { throw new MessagingException("没有发件人!"); } InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; }
/** * * @param tos address String array * @return Address Array * @throws AddressException address convert exception */ protected Address[] toAddresses(final String tos) throws AddressException { if(tos != null && !"".equals(tos)) { final List<Address> to = Lists.newArrayList(); final String[] toArray = tos.split(";"); if(ArrayUtils.isNotEmpty(toArray)) { for(final String address : toArray) { if(StringUtils.isNotBlank(address)) { to.add(new InternetAddress(address.trim())); } } } return to.toArray(new InternetAddress[0]); } return null; }
private void dispatchAnonymousMessage() throws AddressException, MessagingException { int sendDelay = this.config.getInt(ConfigKeys.MAIL_SMTP_DELAY); for (User user : this.users) { if (StringUtils.isEmpty(user.getEmail())) { continue; } if (this.needCustomization) { this.defineUserMessage(user); } Address address = new InternetAddress(user.getEmail()); if (logger.isTraceEnabled()) { logger.trace("Sending mail to: " + user.getEmail()); } this.message.setRecipient(Message.RecipientType.TO, address); Transport.send(this.message, new Address[] { address }); if (sendDelay > 0) { this.waitUntilNextMessage(sendDelay); } } }
@Override public String process() { logger.info("Running inside MailBatchlet batchlet "); String fromAddress = stepContext.getProperties().getProperty("mail.from"); String toAddress = stepContext.getProperties().getProperty("mail.to"); try { MimeMessage m = new MimeMessage(mailSession); Address from = new InternetAddress(fromAddress); Address[] to = new InternetAddress[] { new InternetAddress(toAddress) }; m.setFrom(from); m.setRecipients(TO, to); m.setSubject("Batch on wildfly executed"); m.setSentDate(new java.util.Date()); m.setContent("Job Execution id " + jobContext.getExecutionId() + " warned disk space getting low!", "text/plain"); send(m); } catch (javax.mail.MessagingException e) { logger.log(SEVERE, "error send mail", e); } return COMPLETED.name(); }
/** * This method builds {@link MimeMessage} based on {@link ContentModel} * * @throws MessagingException */ private void buildContentModelMessage() throws MessagingException { Map<QName, Serializable> properties = messageFileInfo.getProperties(); String prop = null; setSentDate(messageFileInfo.getModifiedDate()); // Add FROM address Address[] addressList = buildSenderFromAddress(); addFrom(addressList); // Add TO address addressList = buildRecipientToAddress(); addRecipients(RecipientType.TO, addressList); prop = (String) properties.get(ContentModel.PROP_TITLE); try { prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop; prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null); } catch (UnsupportedEncodingException e) { // ignore } setSubject(prop); setContent(buildContentModelMultipart()); }
public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) { try { Session session = getSession(setup); Address[] tos = new javax.mail.Address[0]; tos = new InternetAddress[]{new InternetAddress(to)}; Address[] froms = new InternetAddress[]{new InternetAddress(from)}; MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setFrom(froms[0]); mimeMessage.setText(msg); Transport.send(mimeMessage, tos); } catch (Throwable e) { throw new RuntimeException(e); } }
/** * Get the recipients of the specified type * * @param recipientType * the type of recipient - to, cc or bcc * @return array with recipients, emtpy array of no recipients of this type * are present * @throws PackageException */ @PublicAtsApi public String[] getRecipients( RecipientType recipientType ) throws PackageException { try { Address[] recipientAddresses = message.getRecipients(recipientType.toJavamailType()); // return an empty string if no recipients are present if (recipientAddresses == null) { return new String[]{}; } String[] recipients = new String[recipientAddresses.length]; for (int i = 0; i < recipientAddresses.length; i++) { recipients[i] = recipientAddresses[i].toString(); } return recipients; } catch (MessagingException me) { throw new PackageException(me); } }
/** * This method resturns only the email address portion of the sender * contained in the first From header * * @return the sender address * @throws PackageException */ @PublicAtsApi public String getSenderAddress() throws PackageException { try { Address[] fromAddresses = message.getFrom(); if (fromAddresses == null || fromAddresses.length == 0) { throw new PackageException("Sender not present"); } InternetAddress fromAddress = (InternetAddress) fromAddresses[0]; return fromAddress.getAddress(); } catch (MessagingException me) { throw new PackageException(me); } }
@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); } }
/** * Given Address[], return a comma-separated string of the email addresses. * @param replyToAddresses * @return return a comma-separated string of the email addresses. */ private String _getAddressString(Address[] replyToAddresses) { StringBuffer to = new StringBuffer(100); for (int i = 0; i < replyToAddresses.length; i++) { if (i > 0) to.append(","); to.append(((InternetAddress)replyToAddresses[i]).getAddress()); } return to.toString(); }
@Test public void register() throws Exception { mockMvc.perform( post(URL_REGISTRATION) .contentType(MediaType.APPLICATION_JSON) .content(asJsonString(new RequestUserDTO(USERNAME, EMAIL_TO, "")))) .andExpect(status().isOk()); MimeMessage[] receivedMessages = testSmtp.getReceivedMessages(); assertEquals(1, receivedMessages.length); MimeMessage message = receivedMessages[0]; assertEquals(EmailSenderImpl.SUBJECT, message.getSubject()); String body = GreenMailUtil.getBody(message).replaceAll("=\r?\n", ""); Address to = message.getAllRecipients()[0]; Address from = message.getFrom()[0]; assertEquals(EMAIL_TO, to.toString()); assertEquals(EmailSenderImpl.EMAIL_FROM, from.toString()); String url = TestUtils.extractLink(body); mockMvc.perform(get(url)) .andExpect(status().isOk()); }
private static Map<String, Object> getParyInfoFromEmailAddress(Address [] addresses, GenericValue userLogin, LocalDispatcher dispatcher) throws GenericServiceException { InternetAddress emailAddress = null; Map<String, Object> map = null; Map<String, Object> result = null; if (addresses == null) { return null; } if (addresses.length > 0) { Address addr = addresses[0]; if (addr instanceof InternetAddress) { emailAddress = (InternetAddress)addr; } } if (emailAddress != null) { map = new HashMap<String, Object>(); map.put("address", emailAddress.getAddress()); map.put("userLogin", userLogin); result = dispatcher.runSync("findPartyFromEmailAddress", map); } return result; }
private static List<Map<String, Object>> buildListOfPartyInfoFromEmailAddresses(Address [] addresses, GenericValue userLogin, LocalDispatcher dispatcher) throws GenericServiceException { InternetAddress emailAddress = null; Map<String, Object> result = null; List<Map<String, Object>> tempResults = new LinkedList<Map<String,Object>>(); if (addresses != null) { for (Address addr: addresses) { if (addr instanceof InternetAddress) { emailAddress = (InternetAddress)addr; if (emailAddress != null) { result = dispatcher.runSync("findPartyFromEmailAddress", UtilMisc.toMap("address", emailAddress.getAddress(), "userLogin", userLogin)); if (result.get("partyId") != null) { tempResults.add(result); } } } } } return tempResults; }
@Test public void shouldRedirectMessage() throws Exception { Session session = Session.getInstance(new Properties()); doReturn(session).when(mailSenderSpy).getMailSession(); Message messageMock = mock(Message.class); doReturn(messageMock).when(mailSenderSpy).initializeMimeMessage(MAIL_BODY, session); doReturn(SENDER_FROM).when(mailSenderSpy).getSenderFrom(); mailSenderSpy.redirectMessage(RECIPIENT, MAIL_BODY); InOrder inOrder = inOrder(messageMock, mailSenderSpy); inOrder.verify(messageMock).setRecipients(TO, new Address[] {}); inOrder.verify(messageMock).setRecipients(CC, new Address[] {}); inOrder.verify(messageMock).setRecipients(BCC, new Address[] {}); inOrder.verify(messageMock).setRecipients(TO, InternetAddress.parse(RECIPIENT)); inOrder.verify(messageMock).setFrom(InternetAddress.parse(SENDER_FROM)[0]); inOrder.verify(mailSenderSpy).sendMessage(messageMock); }
public void send(Mail mail) throws MailerException { Session session = this.criarSession(); MimeMessage message = new MimeMessage(session); MailTemplate template = new MailTemplateVelocity(mail); try { message.setFrom(new InternetAddress(this.getConfig().getRemetente())); Address[] toUser = InternetAddress.parse(mail.getDestinatario()); message.setRecipients(Message.RecipientType.TO, toUser); message.setSubject(mail.getAssunto()); message.setContent(template.getHtml(), "text/html"); Transport.send(message); } catch (Exception e) { throw new MailerException(String.format("Erro ao enviar email: %s", e.getMessage()), e); } }
private Message createMessage(final String emailAddress, final String subjectLine, final Session session, final MimeMultipart mimeMultipart, final ExtensionProperties properties) throws MessagingException { final List<InternetAddress> addresses = new ArrayList<>(); try { addresses.add(new InternetAddress(emailAddress)); } catch (final AddressException e) { log.warn(String.format("Could not create the address from %s: %s", emailAddress, e.getMessage())); } if (addresses.isEmpty()) { throw new RuntimeException("There were no valid email addresses supplied."); } final Message message = new MimeMessage(session); message.setContent(mimeMultipart); message.setFrom(new InternetAddress(properties.getEmailFromAddress())); message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()])); message.setSubject(subjectLine); return message; }
private String getAddresses(MimeMessage mimeMessage, RecipientType recipientType) { try { Address[] addresses = mimeMessage.getRecipients(recipientType); if (addresses == null) { return null; } StringBuilder builder = new StringBuilder(); Address[] arrayOfAddress1; int j = (arrayOfAddress1 = addresses).length; for (int i = 0; i < j; i++) { Address address = arrayOfAddress1[i]; InternetAddress ia = (InternetAddress) address; builder.append(ia.getAddress()).append(";"); } return builder.substring(0, builder.length() - 1); } catch (MessagingException e) { } return ""; }
private String getFrom(MimeMessage mimeMessage) { try { Address[] addresses = mimeMessage.getFrom(); StringBuilder builder = new StringBuilder(); Address[] arrayOfAddress1; int j = (arrayOfAddress1 = addresses).length; for (int i = 0; i < j; i++) { Address address = arrayOfAddress1[i]; InternetAddress ia = (InternetAddress) address; builder.append(ia.getAddress()).append(";"); } return builder.substring(0, builder.length() - 1); } catch (MessagingException e) { } return ""; }
@Override public void sendMessage(Message message, Address[] addresses) throws MessagingException { if ("fail".equals(message.getSubject())) { throw new MessagingException("failed"); } if (!ObjectUtils.nullSafeEquals(addresses, message.getAllRecipients())) { throw new MessagingException("addresses not correct"); } if (message.getSentDate() == null) { throw new MessagingException("No sentDate specified"); } if (message.getSubject() != null && message.getSubject().contains("custom")) { assertEquals(new GregorianCalendar(2005, 3, 1).getTime(), message.getSentDate()); } this.sentMessages.add(message); }
public void init() { if (_toList.size() == 0) throw new ConfigException(L.l("mail service requires at least one 'to' address")); _to = new Address[_toList.size()]; _toList.toArray(_to); _from = new Address[_fromList.size()]; _fromList.toArray(_from); try { if (_session == null) { _session = Session.getInstance(_properties); } Transport smtp = _session.getTransport("smtp"); smtp.close(); } catch (Exception e) { throw ConfigException.wrap(e); } }
/** * Helper method for composing a simple text MIME Message with the source. * If from address is null, will use the internet address of the local host. * * @param source * @return * @throws SmtpMailException */ private SMTPMessage composeMessage(String source, Address from, Address[] to, String subject) throws SmtpMailException { SMTPMessage msg = new SMTPMessage(session); try { if (from == null) { msg.setFrom(); } else { msg.setFrom(from); } msg.setSubject(subject); msg.setRecipients(Message.RecipientType.TO, to); msg.setText(source); msg.setSentDate(new Date()); return msg; } catch (MessagingException e) { throw new SmtpMailException("Error creating the message.", e); } }
/** * ����ʼ������� * @param msg �ʼ����� * @return ���� <Email��ַ> */ public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom(); if (froms.length < 1){ //return "ϵͳ�ָ�"; throw new MessagingException("û�з�����!"); } InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; }
/** * �����ռ������ͣ���ȡ�ʼ��ռ��ˡ����ͺ����͵�ַ������ռ�������Ϊ�գ��������е��ռ��� * <p>Message.RecipientType.TO �ռ���</p> * <p>Message.RecipientType.CC ����</p> * <p>Message.RecipientType.BCC ����</p> * @param msg �ʼ����� * @param type �ռ������� * @return �ռ���1 <�ʼ���ַ1>, �ռ���2 <�ʼ���ַ2>, ... */ public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException { StringBuffer receiveAddress = new StringBuffer(); Address[] addresss = null; if (type == null) { addresss = msg.getAllRecipients(); } else { addresss = msg.getRecipients(type); } if (addresss == null || addresss.length < 1) throw new MessagingException("û���ռ���!"); for (Address address : addresss) { InternetAddress internetAddress = (InternetAddress)address; receiveAddress.append(internetAddress.toUnicodeString()).append(","); } receiveAddress.deleteCharAt(receiveAddress.length()-1); //ɾ�����һ������ return receiveAddress.toString(); }
/** * Finds the relevant users for a task instance and returns their e-mail addresses * @param taskInstance * @return an array with the valid e-mail addresses */ protected Address[] getTaskUserEmailAddresses(TaskInstance taskInstance) throws ObserverException { try { List<String> groups; if (taskInstance.isTemplateBased()) groups = taskInstance.getGroups(); else groups = ServiceLocator.getTaskServices().getGroupsForTaskInstance(taskInstance); return toMailAddresses(getGroupEmails(groups)); } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); throw new ObserverException(-1, ex.getMessage(), ex); } }
/** * 获得邮件发件人 * @param msg 邮件内容 * @return 姓名 <Email地址> * @throws MessagingException * @throws UnsupportedEncodingException */ public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom(); if (froms.length < 1) throw new MessagingException("没有发件人!"); InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; }
/** * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人 * <p>Message.RecipientType.TO 收件人</p> * <p>Message.RecipientType.CC 抄送</p> * <p>Message.RecipientType.BCC 密送</p> * @param msg 邮件内容 * @param type 收件人类型 * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ... * @throws MessagingException */ public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException { StringBuffer receiveAddress = new StringBuffer(); Address[] addresss = null; if (type == null) { addresss = msg.getAllRecipients(); } else { addresss = msg.getRecipients(type); } if (addresss == null || addresss.length < 1) throw new MessagingException("没有收件人!"); for (Address address : addresss) { InternetAddress internetAddress = (InternetAddress)address; receiveAddress.append(internetAddress.toUnicodeString()).append(","); } receiveAddress.deleteCharAt(receiveAddress.length()-1); //删除最后一个逗号 return receiveAddress.toString(); }
/** * Verifies that no email address in TO, BCC and CC headers ends with * {@link MailMessageHelper#ANONYMOUS_EMAIL_ADDRESS_SUFFIX}. In case such an email address is * encountered an {@link InvalidRecipientMailAddressException} will be thrown. * * @param message * the message to check * @throws MessagingException * in case the message has no recipients or getting the recipients failed * @throws InvalidRecipientMailAddressException * in case an anonymous recipient is encountered */ public static void assertNonAnonymousRecipients(Message message) throws MessagingException, InvalidRecipientMailAddressException { Address[] addresses = message.getAllRecipients(); if (addresses == null || addresses.length == 0) { throw new MessagingException("Message has no recipients"); } for (Address a : addresses) { if (a instanceof InternetAddress) { String email = ((InternetAddress) a).getAddress(); if (isAnonymousEmailAddress(email)) { throw new InvalidRecipientMailAddressException( "Recipient address ends with the anonymous email address suffix.", email); } } } }
/** * Extract recipients from the message by evaluating the provided recipient type. * * @param message * the message to check * @param recipientType * the recipient header to evaluate * @param recipients * storage for the found recipients * @param suffixFilter * optional filter to restrict results to email addresses that end with the suffix. * If null all values will be accepted. * @throws MessagingException * in case of an error while reading the recipients */ private static void extractRecipients(Message message, Message.RecipientType recipientType, Set<String> recipients, String suffixFilter) throws MessagingException { Address[] addresses = message.getRecipients(recipientType); if (addresses != null) { String lowerSuffix = suffixFilter == null ? null : suffixFilter .toLowerCase(Locale.ENGLISH); for (Address a : addresses) { if (a instanceof InternetAddress) { String addressString = ((InternetAddress) a).getAddress(); if (lowerSuffix != null) { if (addressString.toLowerCase(Locale.ENGLISH).endsWith(lowerSuffix)) { recipients.add(addressString); } } else { recipients.add(addressString); } } } } }
static void listFolder(Folder folder, String tab, boolean recurse) throws Exception { folder.open(Folder.READ_WRITE); System.out.println(tab + "Name: " + folder.getName() + '(' + folder.getFullName() + ')'); if (!folder.isSubscribed()) System.out.println(tab + "Not Subscribed"); if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (folder.hasNewMessages()) System.out.println(tab + "Has New Messages"); else System.out.println(tab + "No New Messages"); Message[] msgs = folder.getMessages(); for (Message m : msgs) { Address from = m.getFrom()[0]; String fromAddress; if (from instanceof InternetAddress) fromAddress = ((InternetAddress)from).getAddress(); else fromAddress = from.toString(); StringBuffer sb = new StringBuffer(); fromFmt.format(fromAddress, sb, null); sb. append(" "); subjFmt.format(m.getSubject(), sb, null); System.out.println(sb.toString()); } } if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { System.out.println(tab + "Is Directory"); } if (recurse) { Folder[] fs = folder.list(); for (Folder f : fs) { listFolder(f, tab + "", recurse); } } }
public String toString() { try { Address from = m.getFrom()[0]; String fromAddress; if (from instanceof InternetAddress) fromAddress = ((InternetAddress)from).getAddress(); else fromAddress = from.toString(); StringBuffer sb = new StringBuffer(); fromFmt.format(fromAddress, sb, null); sb. append(" "); subjFmt.format(m.getSubject(), sb, null); return sb.toString(); } catch (Exception e) { return e.toString(); } }
private void sendEmail(JSONObject msg, String type){ try{ Properties props = new Properties(); Authenticator auth = new EmailAutherticator(senderUsername,senderPassword); props.put("mail.smtp.host", mailHost); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, auth); MimeMessage message = new MimeMessage(session); Address address = new InternetAddress(senderUsername); message.setFrom(address); message.setSubject("dChat SDK Server [ "+type+" ] Mail"); message.setText(msg.toString(), "UTF-8"); message.setHeader("dChat SDK Server", type); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, new Address[]{address}); Transport.send(message); }catch(Exception e){ LOG.error("send notifier email failed! "+e.getMessage(), e); } LOG.info("Send Exception/Error Notifier Email to Admin Success!"); }
private cfArrayData getAddresses( Address[] a ){ try{ cfArrayData arr = cfArrayData.createArray( 1 ); for ( int x=0; x < a.length; x++ ){ InternetAddress address = (InternetAddress)a[x]; cfStructData s = new cfStructData(); s.setData("name", new cfStringData(address.getPersonal())); s.setData("email", new cfStringData(address.getAddress())); arr.addElement( s ); } return arr; }catch(Exception e){ return cfArrayData.createArray( 1 ); } }
public Address[] getAllRecipients() { Address[] address = null; Optional<String[]> optional = Optional.ofNullable(recipients); if (optional.isPresent()) { address = Arrays.stream(optional.get()).map(s -> { InternetAddress internetAddress = null; try { internetAddress = new InternetAddress(s); } catch (AddressException e) { } return internetAddress; }).toArray(InternetAddress[]::new); } return address; }
@Override public void onSend(SubEthaMessage msg, SendFilterContext ctx) throws IgnoreException, MessagingException { log.log(Level.FINE,"ReplyToFilter: onSend()"); InternetAddress addr = new InternetAddress(); Boolean replyToList = (Boolean) ctx.getArgument(ARG_MAILINGLIST); String emailAddress = (String) ctx.getArgument(ARG_EMAILADDRESS); // if nothing is selected, then default to reply to the list. if (replyToList.booleanValue() || emailAddress == null || emailAddress.length() == 0) { addr.setAddress(ctx.getList().getEmail()); } else { addr.setAddress(emailAddress); } Address[] addrs = {addr}; msg.setReplyTo(addrs); }
/** * @return the first found of Sender, From, or envelope sender * @throws MessagingException */ public InternetAddress getSenderWithFallback(String envelopeSender) throws MessagingException { // Convoluted process to determine sender. // Check, in order: Sender field, first entry of From field, envelope sender InternetAddress senderField = (InternetAddress)this.getSender(); if (senderField == null) { Address[] froms = this.getFrom(); if (froms != null && froms.length > 0) senderField = (InternetAddress)froms[0]; else senderField = new InternetAddress(envelopeSender); } return senderField; }
public EmailService(JavaMailSender mailSender, String supportEmail, String personalName) throws UnsupportedEncodingException { if(mailSender==null) { throw new IllegalArgumentException("EmailService constructor contains a null JavaMailSender argument"); } if(supportEmail==null) { throw new IllegalArgumentException("EmailService constructor contains a null String argument"); } Address[] temp = null; try { temp = new Address[] {new InternetAddress(supportEmail, personalName)}; } catch (IllegalArgumentException e) { LOGGER.error(e); } this.senderAddresses = temp; this.mailSender = mailSender; }
@Test public void addInvitation_sendInvitation_properConfiguration() throws MessagingException, UnsupportedEncodingException { MockitoAnnotations.initMocks(this); when(detailsFinder.findUserName(any(Authentication.class))).thenReturn(USER); when(mailSender.createMimeMessage()).thenReturn(mimeMessage); setUpNotExistingUserRequest(INVITATION_MAIL); when(accessInvitationsService.getAccessInvitations(INVITATION_MAIL)).thenReturn(Optional.empty()); when(invitationLinkGenerator.getLink(anyString())).thenReturn("http://example.com"); InvitationModel invitation = InvitationModel.of(INVITATION_MAIL, false); ResponseEntity<String> response = postForEntityWithToken(restTemplate, TOKEN, baseUrl + "rest/invitations", invitation, String.class); assertEquals(response.getStatusCode(), HttpStatus.OK); verify(mailSender).send(any(MimeMessage.class)); verify(mimeMessage).addRecipients(any(Message.RecipientType.class), eq(INVITATION_MAIL)); verify(mimeMessage).addFrom((Address[]) addressCaptor.capture()); Address[] addresses = (Address[]) addressCaptor.getValue(); assertEquals(new InternetAddress(SUPPORT_EMAIL, EMAIL_NAME), addresses[0]); }
/** * 以HTML格式发送邮件. * * @param mailSender 待发送的邮件信息 * @return Boolean */ protected boolean sendHtmlMail(final AbstractMailSender mailSender) { final Properties pro = mailSender.getProperties(); MailAuthenticator authenticator = null; if (mailSender.isValidate()) { authenticator = new MailAuthenticator(mailSender.getUserName(), mailSender.getPassword()); } final Session sendMailSession; if(singletonSessionInstance) { sendMailSession = Session.getDefaultInstance(pro, authenticator); } else { sendMailSession = Session.getInstance(pro, authenticator); } sendMailSession.setDebug(debugEnabled); try { final Message mailMessage = new MimeMessage(sendMailSession); final Address from = new InternetAddress(mailSender.getFromAddress()); mailMessage.setFrom(from); mailMessage.setRecipients(Message.RecipientType.TO, toAddresses(mailSender.getToAddress())); mailMessage.setSubject(mailSender.getSubject()); mailMessage.setSentDate(new Date()); final Multipart mainPart = new MimeMultipart(); final BodyPart html = new MimeBodyPart(); html.setContent(mailSender.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); mailMessage.setContent(mainPart); Transport.send(mailMessage); return true; } catch (final MessagingException ex) { LOGGER.error(ex.getMessage(), ex); } return false; }