@Override public void sendEmail(final UserDTO user, String url) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(user.getEmail()); message.setSubject(SUBJECT); message.setFrom(EMAIL_FROM); // could be parameterized... Map model = new HashMap(); model.put("user", user); model.put("url", url); String text = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "org/enricogiurin/sushibar/registration-confirmation.vm", model); message.setText(text, true); } }; this.emailSender.send(preparator); }
@Test public void toJsonAsStringShouldReturnTextBodyWhenMultipartAndTextHtml() throws Exception { MimeMessage message = MimeMessageBuilder.mimeMessageBuilder() .setMultipartWithBodyParts( MimeMessageBuilder.bodyPartBuilder() .data("<p>this is my body</p>") .type("text/html") .build()) .addHeader("Date", "Wed, 24 May 2017 06:23:11 -0700") .build(); FakeMail mail = FakeMail.from(message); ClassificationRequestBodySerializer testee = new ClassificationRequestBodySerializer(mail, new FakeUUIDGenerator()); String jsonAsString = testee.toJsonAsString(); assertThatJson(jsonAsString) .isEqualTo("{\"messageId\":\"524e4f85-2d2f-4927-ab98-bd7a2f689773\"," + "\"from\":[]," + "\"recipients\":{\"to\":[],\"cc\":[],\"bcc\":[]}," + "\"subject\":[\"\"]," + "\"date\":\"2017-05-24T13:23:11Z\"," + "\"textBody\":\"this is my body\\n\\n\"}"); }
/** * 发送邮件,从公邮里发邮件给成员变量email。 * * @throws Exception 可能会有异常抛出,建议打出Log。 */ public void sendCodeMail() throws MessagingException, UnsupportedEncodingException { if (email == null) { Log.e("sendCodeMail","调用错误"); return; } //创建一封邮件 MimeMessage message = createCodeMessage(session, myEmailAccount, email); Transport transport = session.getTransport(); //使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错 transport.connect(myEmailAccount, myEmailPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
public void sendMailBatch(List<String> to, String title, String content) throws MessagingException { Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); to.forEach(address -> { try { message.addRecipient(Message.RecipientType.TO, new InternetAddress(address)); } catch (MessagingException ignored) { } }); message.setSubject(title); message.setContent(content, "text/html;charset=UTF-8"); Transport.send(message); }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithNewPassword( @NotBlank @Email final String email, @NotBlank final String newPassword ) { log.info("Called with e-mail {}, newPassword {}", email, newPassword); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Recover password"); helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }
@Test @RunAsStudent public void testAbortPrivateExam() throws Exception { Exam studentExam = createPrivateStudentExam(); Result result = request(Helpers.PUT, String.format("/app/student/exam/abort/%s", studentExam.getHash()), null); assertThat(result.status()).isEqualTo(200); // Check that correct mail was sent assertThat(greenMail.waitForIncomingEmail(MAIL_TIMEOUT, 1)).isTrue(); MimeMessage[] mails = greenMail.getReceivedMessages(); assertThat(mails).hasSize(1); assertThat(mails[0].getFrom()[0].toString()).contains(ConfigFactory.load().getString("sitnet.email.system.account")); assertThat(mails[0].getSubject()).isEqualTo("Personal exam has been abandoned"); String body = GreenMailUtil.getBody(mails[0]); // Make sure there is no link to review assertThat(body).doesNotContain("<a href"); }
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); }
/** * 创建一封只包含文本的简单邮件 * * @param session * 和服务器交互的会话 * @param sendMail * 发件人邮箱 * @param receiveMail * 收件人邮箱 * @return * @throws Exception */ public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String username,String pwd) throws Exception { // 1. 创建一封邮件 MimeMessage message = new MimeMessage(session); // 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称) message.setFrom(new InternetAddress(sendMail, "Mircle", "UTF-8")); // 3. To: 收件人(可以增加多个收件人、抄送、密送) message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8")); // 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题) message.setSubject(subject, "UTF-8"); // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容) message.setContent(getContent(username,pwd), "text/html;charset=UTF-8"); // 6. 设置发件时间 message.setSentDate(new Date()); // 7. 保存设置 message.saveChanges(); return message; }
public static void sendAccountActivateEmail(String email, String uuid, int userId) { Session session; try { session = getSession(); MimeMessage message = new MimeMessage(session); message.setSubject("������֤��"); message.setSentDate(new Date()); message.setFrom(new InternetAddress(FROM)); message.setRecipient(RecipientType.TO, new InternetAddress(email)); message.setContent("�����û�"+userId+":������֤��Ϊ��"+uuid, "text/html;charset=utf-8"); message.saveChanges(); Transport.send(message); } catch (Exception e) { e.printStackTrace(); } }
/** * * @param session 和服务器交互的会话 * @param mail 邮件内容 * @return * @throws Exception */ private static MimeMessage createMimeMessage(Session session, String SendAccount, Mail mail) throws Exception { MimeMessage message = new MimeMessage(session); //From: 发件人 message.setFrom(new InternetAddress(SendAccount, mail.getPersonal(), "UTF-8")); // To: 收件人 message.setRecipients(MimeMessage.RecipientType.TO, mail.getAddresses()); // Subject: 邮件主题 message.setSubject(mail.getSubject(), "UTF-8"); // Content: 邮件正文(可以使用html标签) message.setContent(mail.getContext(), "text/html;charset=UTF-8"); // 设置发件时间 message.setSentDate(new Date()); message.saveChanges(); return message; }
private void sendMail(SendMailActionMsg msg) throws MessagingException { log.debug("Sending mail {}", msg); MimeMessage mailMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mailMsg, "UTF-8"); helper.setFrom(msg.getFrom()); helper.setTo(msg.getTo()); if (!StringUtils.isEmpty(msg.getCc())) { helper.setCc(msg.getCc()); } if (!StringUtils.isEmpty(msg.getBcc())) { helper.setBcc(msg.getBcc()); } helper.setSubject(msg.getSubject()); helper.setText(msg.getBody()); mailSender.send(helper.getMimeMessage()); log.debug("Mail sent {}", msg); }
@Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } }
@Override protected void sendMessageImpl(_BridgeSubscription sub, _MatrixBridgeMessage msg) { log.info("Email bridge: sending message from {} to {} - start", msg.getSender(), getIdentity()); try { Optional<MimeMessage> mimeMsg = formatter.get(sub, msg); if (!mimeMsg.isPresent()) { log.info("Email bridge: formatter did not return any content for matrix message, ignoring"); } else { send(mimeMsg.get()); log.info("Email bridge: sending message from {} to {} - success", msg.getSender(), getIdentity()); } } catch (Exception e) { log.error("Email bridge: sending message from {} to {} - failure", msg.getSender(), getIdentity()); throw new RuntimeException(e); } log.info("Email bridge: sending message from {} to {} - end", msg.getSender(), getIdentity()); }
/** * 发送html邮件 */ @Async("mailAsync") public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setSentDate(new Date()); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } }
protected MimeMessage sendMessage(String from, String subject, String template, final Action mailAction) { if (from != null) { mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, from); } mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject); mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template); mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel()); RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class); return txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>() { @Override public MimeMessage execute() throws Throwable { ACTION_SERVICE.executeAction(mailAction, null); return ACTION_EXECUTER.retrieveLastTestMessage(); } }, true); }
public static boolean createMimeMessage() { try { // 用props对象来创建并初始化session对象 session = Session.getDefaultInstance(props, null); // 用session对象来创建并初始化邮件对象 message = new MimeMessage(session); // 生成附件组件的实例 mp = new MimeMultipart(); } catch (Exception e) { return false; } return true; }
@Override protected int prepare(MimeMessage mimeMessage, Newsletter entity, Proband recipient) throws Exception { //http://www.javabeat.net/how-to-send-email-using-spring-framework/ return 0; }
/** * Convenience method which creates a new {@link MimeMessage} from an input stream */ public static MimeMessage newMimeMessage(InputStream inputStream) { try { return new MimeMessage(Session.getDefaultInstance(new Properties()), inputStream); } catch (MessagingException e) { throw new RuntimeException(e); } }
/** * This method will convert a MIME message to meta data * * @param mimeMessage the input MimeMessage instance * @return the MetaData produced * @throws RbvStorageException */ protected ImapMetaData createImapMetaData( MimeMessage mimeMessage ) throws RbvException { try { MimePackage mimePackage = new MimePackage(mimeMessage); ImapMetaData metaData = new ImapMetaData(mimePackage); return metaData; } catch (PackageException pe) { throw new RbvStorageException("Could not get meta data from " + getDescription(), pe); } }
private MimePackage( String parentNestedPath, int previousSiblings, MimeMessage message, Folder folder ) throws PackageException { setNestedPath(parentNestedPath, previousSiblings); this.message = message; this.partOfImapFolder = folder; decompose(); }
private static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); email.setText(bodyText); return email; }
private MimeMessage createMessage(Session session, String body) { try { MimeMessage mesage = new MimeMessage(session); mesage.setSubject("Test Mail"); mesage.setText(body); return mesage; } catch (MessagingException e) { throw new RuntimeException(e); } }
/** * @return Returns all messags in all folders for all users * {@link GreenMailUtil} has a bunch of static helper methods to extract body text etc. */ public MimeMessage[] getReceivedMessages() { List msgs = managers.getImapHostManager().getAllMessages(); MimeMessage[] ret = new MimeMessage[msgs.size()]; for (int i = 0; i < msgs.size(); i++) { SimpleStoredMessage simpleStoredMessage = (SimpleStoredMessage) msgs.get(i); ret[i] = simpleStoredMessage.getMimeMessage(); } return ret; }
private void sendSimpleMailWithAttachment(final String fromAddress, final List<String> toAddress, final List<String> ccAddress, final String subject, final String mailContent, final List<MultipartFile> attachFiles) { mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); messageHelper.setFrom(fromAddress); messageHelper.setTo(toAddress.toArray(new String[toAddress.size()])); if (ccAddress != null && ccAddress.size() > 0) { messageHelper.setCc(ccAddress.toArray(new String[ccAddress.size()])); } messageHelper.setSubject(subject); messageHelper.setText(mailContent); for (final MultipartFile attachFile : attachFiles) { // determines if there is an upload file, attach it to the e-mail if (attachFile != null) { String attachName = attachFile.getOriginalFilename(); messageHelper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } else { log.info("Attached file is Empty. Skipping the file " + attachFile + " in mail."); } } } }); }
/** * {@inheritDoc} */ @Async @Override public void sendMailWithActivationToken( @NotBlank @Email final String email, @NotBlank final String token ) { log.info("Called with e-mail {}, token {}", email, token); try { final JavaMailSenderImpl sender = new JavaMailSenderImpl(); final MimeMessage message = sender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(email); helper.setSubject("Complete registration"); helper.setText("To activation your account, click the link below:<br />" + "<a href='" + "https://localhost:8443" + "/register/thanks?token=" + token + "'>" + "Click here to complete your registration" + "</a>", true); sendMail(message); } catch (MessagingException e) { e.printStackTrace(); } }