Java Code Examples for org.springframework.mail.javamail.MimeMessageHelper#setFrom()

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper#setFrom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmailServiceImpl.java    From tutorials with MIT License 8 votes vote down vote up
@Override
public void sendMessageWithAttachment(String to,
                                      String subject,
                                      String text,
                                      String pathToAttachment) {
    try {
        MimeMessage message = emailSender.createMimeMessage();
        // pass 'true' to the constructor to create a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(NOREPLY_ADDRESS);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
        helper.addAttachment("Invoice", file);

        emailSender.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: MailTool.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 7 votes vote down vote up
@SneakyThrows
public void sendHtml(String subjct, String text, String... to) {
	MimeMessage mimeMessage = mailSender.createMimeMessage();

	MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

	messageHelper.setFrom(from);
	messageHelper.setTo(to);
	messageHelper.setSubject(subjct);

	// html格式,第二个参数为true
	messageHelper.setText(text, true);

	// 附件
	// messageHelper.addAttachment

	jmsTool.sendMessage(JMSType.SEND_MAIL, mimeMessage);
}
 
Example 3
Source File: MailServiceImpl.java    From Jantent with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to
 * @param subject
 * @param content
 * @param filepath
 */
@Override
public void sendFileMail(String to, String subject, String content, String filepath) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setFrom(mailFrom);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content,true);

        FileSystemResource file = new FileSystemResource(new File(filepath));
        String fileName = filepath.substring(filepath.lastIndexOf(File.separator));
        helper.addAttachment(fileName,file);

        mailSender.send(mimeMessage);

    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 4
Source File: MailService.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@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, StandardCharsets.UTF_8.name());
        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());
        }
    }
}
 
Example 5
Source File: MailSender.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 发送html邮件
 */
public void sendHtmlMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setFrom(this.getFrom());
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("发送邮件异常! from: " + name+ "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example 6
Source File: MailServiceImpl.java    From Java-API-Test-Examples with Apache License 2.0 6 votes vote down vote up
/**
 * 发送正文中有静态资源(图片)的邮件
 * @param to
 * @param subject
 * @param content
 * @param rscPath
 * @param rscId
 */
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
    MimeMessage message = mailSender.createMimeMessage();

    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource res = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, res);

        mailSender.send(message);
        log.info("嵌入静态资源的邮件已经发送。");
    } catch (MessagingException e) {
        log.error("发送嵌入静态资源的邮件时发生异常!", e);
    }
}
 
Example 7
Source File: MailService.java    From cloud-portal with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void send(String to, String subject, String templatePath, List<File> attachmentList, Map variableMap) {

	// logging
	LOG.info("Sending mail from '{}' to address '{}' and cc addresses '{}' with subject '{}'", from, to, cc, subject);

	// really send mail
	if (send) {

		// create mime message preparator
		MimeMessagePreparator preparator = new MimeMessagePreparator() {

			@SuppressWarnings("unchecked")
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {

				// get mail text by substituting variables in mail template with velocity
				String text = velocityService.evaluate(templatePath, variableMap);

				// create message helper
				MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
				messageHelper.setFrom(from);
				messageHelper.setTo(to);
				messageHelper.setCc(cc.split(","));
				messageHelper.setSubject(subject);
				messageHelper.setText(text, true);
				
				// add attachments if available
				for (File file : attachmentList) {
					messageHelper.addAttachment(file.getName(), file);
				}
			}
		};

		// send HTML mail
		mailSender.send(preparator);
	}
}
 
Example 8
Source File: MailAdapter.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
public void notifyUsersAboutProject(OpenProjectData data) {
  if (!isMailEnabled) {
    logger.debug("Do not send email, because property mail.enabled is set to false.");
    return;
  }
  String recipient = manager.getUserEmail();
  MimeMessagePreparator messagePreparator =
      mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom(mailSenderAddress);
        messageHelper.setTo(recipient);
        messageHelper.setSubject("ODS Project provision update");
        messageHelper.setText(build(data), true);
      };

  Thread sendThread =
      new Thread(
          () -> {
            try {
              MDC.put(STR_LOGFILE_KEY, data.projectKey);
              mailSender.send(messagePreparator);
            } catch (MailException e) {
              logger.error("Error in sending mail for project: " + data.projectKey, e);
            } finally {
              MDC.remove(STR_LOGFILE_KEY);
            }
          });

  sendThread.start();
  logger.debug("Mail for project: {} sent", data.projectKey);
}
 
Example 9
Source File: MailSender.java    From cola-cloud with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        JavaMailSenderImpl js=new JavaMailSenderImpl();
        js.setHost("smtp.qq.com");
        js.setUsername("[email protected]");
        js.setPassword("mygdzwlcjlxpbghc");
        Properties props = new Properties();
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.ssl.enable", true);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.timeout", 25000);
        js.setJavaMailProperties(props);
        MimeMessage message = null;
        try {
            message = js.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
           // helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
            helper.setFrom("[email protected]");
            helper.setTo("[email protected]");
            helper.setSubject("测试");
            helper.setText("测试内容");
            //addAttachmentStatic(helper,params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        js.send(message);
    }
 
Example 10
Source File: EmailServiceImpl.java    From tutorials with MIT License 5 votes vote down vote up
private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException {

        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(NOREPLY_ADDRESS);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlBody, true);
        helper.addInline("attachment.png", resourceFile);
        emailSender.send(message);
    }
 
Example 11
Source File: EmailMimeMessagePreparator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public MimeMessagePreparator prepareMessage(String to, String subject, String body) {
    return mimeMessage -> {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        message.setFrom(msgFrom);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body, true);
    };
}
 
Example 12
Source File: ResetPasswordEmailTransformer.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@Transformer
public MimeMessage transform(final ResetPassword resetPassword) throws MessagingException, IOException {
	MimeMessage message = getEmailSender().createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message);
	helper.setTo(resetPassword.getUser().getEmail());
	helper.setFrom(getDefaultFromAddress(), getDefaultFromName());
	helper.setReplyTo(getDefaultFromAddress());
	helper.setSubject(getSubject());
	Map<String, Object> model = buildModel(resetPassword);
	helper.setText(getText(model), true);
	return message;
}
 
Example 13
Source File: MailServiceImpl.java    From nimrod with MIT License 5 votes vote down vote up
private void sendMimeMailMessage(String from, String[] toArray, String subject, String text, boolean html) throws MessagingException {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
    mimeMessageHelper.setFrom(from);
    mimeMessageHelper.setTo(toArray);
    mimeMessage.setSubject(subject);
    mimeMessageHelper.setText(text, html);
    javaMailSender.send(mimeMessage);
}
 
Example 14
Source File: AbstractTest.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
protected void send() throws Exception {
  try (ClosableSmtpConnection connection = smtpConnectionPool.borrowObject()) {
    MimeMessage mimeMessage = new MimeMessage(connection.getSession());
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
    mimeMessageHelper.addTo("[email protected]");
    mimeMessageHelper.setFrom("[email protected]");
    mimeMessageHelper.setSubject("foo");
    mimeMessageHelper.setText("example", false);
    connection.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
  }
}
 
Example 15
Source File: EmailServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@Override
public void sendHtmlMail(String to, String title, String content) {
    EmailSetting emailSetting = configService.selectConfigByConfigKey(ConfigKey.CONFIG_KEY_EMAIL_SETTING, EmailSetting.class);
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setUsername(emailSetting.getUser());
    mailSender.setHost(emailSetting.getHost());
    mailSender.setDefaultEncoding("utf-8");
    mailSender.setPassword(emailSetting.getPassword());
    mailSender.setPort(emailSetting.getPort());

    Properties properties = new Properties();
    properties.put("mail.smtp.host", emailSetting.getHost());
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
    properties.put("mail.smtp.port", emailSetting.getPort());
    properties.put("mail.smtp.socketFactory.port", emailSetting.getPort());
    properties.put("mail.smtp.ssl.enable", true);
    Session session = Session.getInstance(properties);

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(emailSetting.getFromEmail());
        mimeMessageHelper.setTo(to);
        if (StringUtils.isNotEmpty(emailSetting.getStationmasterEmail())) {
            mimeMessageHelper.setBcc(emailSetting.getStationmasterEmail());
        }
        mimeMessageHelper.setSubject(title);
        mimeMessageHelper.setText(content, true);
        mailSender.setSession(session);
        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
       log.error(e.getMessage(), e);
    }
}
 
Example 16
Source File: NotificationEmailSender.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void prepareMessage(MimeMessage mimeMessage, Notification notification, Staff recipient, StringBuilder text, Date now) throws Exception {
	if (!Settings.getBoolean(SettingCodes.EMAIL_NOTIFICATIONS_ENABLED, Bundle.SETTINGS, DefaultSettings.EMAIL_NOTIFICATIONS_ENABLED)) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_NOTIFICATIONS_DISABLED);
	}
	MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, getEncoding());
	String subject = notification.getSubject();
	if (!CommonUtil.isEmptyString(subject)) {
		mimeMessageHelper.setSubject(subject);
	} else {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_EMPTY_SUBJECT);
	}
	String message = notification.getMessage();
	if (!CommonUtil.isEmptyString(message)) {
		mimeMessageHelper.setText(message, isHtml());
		text.append(message);
	} else {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_EMPTY_MESSAGE);
	}
	mimeMessageHelper.setFrom(Settings.getEmailNotificationFromAddress(), Settings.getEmailNotificationFromName());
	StaffOutVO recipientVO = staffDao.toStaffOutVO(recipient);
	Iterator<StaffContactDetailValue> contactsIt = recipient.getContactDetailValues().iterator();
	while (contactsIt.hasNext()) {
		StaffContactDetailValue contact = contactsIt.next();
		ContactDetailType contactType;
		if (!contact.isNa() && contact.isNotify() && (contactType = contact.getType()).isEmail()) {
			mimeMessageHelper.addTo(contact.getValue(),
					MessageFormat.format(EMAIL_TO_PERSONAL_NAME, recipientVO.getName(), L10nUtil.getContactDetailTypeName(Locales.NOTIFICATION, contactType.getNameL10nKey())));
		}
	}
}
 
Example 17
Source File: MailController.java    From parker with MIT License 4 votes vote down vote up
@ApiOperation("发送HTML格式的邮件")
@PostMapping("send/html")
public BaseResult sendHtml(@RequestBody MailHtmlMessageDto dto){
    BaseResult result = new BaseResult();

    if(StringUtils.isBlank(dto.getTo())){
        result.setData(0);
        result.setMessage("缺少收信人");
        return result;
    }

    if(StringUtils.isBlank(dto.getSubject())){
        result.setData(0);
        result.setMessage("缺少主题");
        return result;
    }

    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    try {
        // true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(dto.getTo());
        helper.setSubject(dto.getSubject());

        // 创建邮件正文
        Context context = new Context();
        if(StringUtils.isNotBlank(dto.getParams())){
            JSONObject params = JSONObject.parseObject(dto.getParams());
            context.setVariables(params);
        }
        String text = templateEngine.process(dto.getMailCode(), context);

        if(StringUtils.isNotBlank(text)){
            helper.setText(text, true);
        }else{
            result.setData(0);
            result.setMessage("缺少内容");
            return result;
        }

        javaMailSender.send(mimeMessage);
    } catch (Exception e) {
        result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        result.setMessage(e.getMessage());
        log.error("发送HTML格式的邮件参数错误{}", e.getMessage());
        e.printStackTrace();
    }
    return result;
}
 
Example 18
Source File: UserService.java    From wallride with Apache License 2.0 4 votes vote down vote up
public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
	User user = userRepository.findOneByEmail(request.getEmail());
	if (user == null) {
		throw new EmailNotFoundException();
	}

	LocalDateTime now = LocalDateTime.now();
	PasswordResetToken passwordResetToken = new PasswordResetToken();
	passwordResetToken.setUser(user);
	passwordResetToken.setEmail(user.getEmail());
	passwordResetToken.setExpiredAt(now.plusHours(24));
	passwordResetToken.setCreatedAt(now);
	passwordResetToken.setCreatedBy(user.toString());
	passwordResetToken.setUpdatedAt(now);
	passwordResetToken.setUpdatedBy(user.toString());
	passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

	try {
		Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
		String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

		ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
		if (blog.isMultiLanguage()) {
			builder.path("/{language}");
		}
		builder.path("/password-reset");
		builder.path("/{token}");

		Map<String, Object> urlVariables = new LinkedHashMap<>();
		urlVariables.put("language", request.getLanguage());
		urlVariables.put("token", passwordResetToken.getToken());
		String resetLink = builder.buildAndExpand(urlVariables).toString();

		Context ctx = new Context(LocaleContextHolder.getLocale());
		ctx.setVariable("passwordResetToken", passwordResetToken);
		ctx.setVariable("resetLink", resetLink);

		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
		message.setSubject(MessageFormat.format(
				messageSourceAccessor.getMessage("PasswordResetSubject", LocaleContextHolder.getLocale()),
				blogTitle));
		message.setFrom(mailProperties.getProperties().get("mail.from"));
		message.setTo(passwordResetToken.getEmail());

		String htmlContent = templateEngine.process("password-reset", ctx);
		message.setText(htmlContent, true); // true = isHtml

		mailSender.send(mimeMessage);
	} catch (MessagingException e) {
		throw new ServiceException(e);
	}

	return passwordResetToken;
}
 
Example 19
Source File: AbstractMailService.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Send mail template.
 *
 * @param callback mime message callback.
 */
protected void sendMailTemplate(@Nullable Callback callback) {
    if (callback == null) {
        log.info("Callback is null, skip to send email");
        return;
    }

    // check if mail is enable
    Boolean emailEnabled = optionService.getByPropertyOrDefault(EmailProperties.ENABLED, Boolean.class);

    if (!emailEnabled) {
        // If disabled
        log.info("Email has been disabled by yourself, you can re-enable it through email settings on admin page.");
        return;
    }

    // get mail sender
    JavaMailSender mailSender = getMailSender();
    printMailConfig();

    // create mime message helper
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage());

    try {
        // set from-name
        messageHelper.setFrom(getFromAddress(mailSender));
        // handle message set separately
        callback.handle(messageHelper);

        // get mime message
        MimeMessage mimeMessage = messageHelper.getMimeMessage();
        // send email
        mailSender.send(mimeMessage);

        log.info("Sent an email to [{}] successfully, subject: [{}], sent date: [{}]",
            Arrays.toString(mimeMessage.getAllRecipients()),
            mimeMessage.getSubject(),
            mimeMessage.getSentDate());
    } catch (Exception e) {
        throw new EmailException("邮件发送失败,请检查 SMTP 服务配置是否正确", e);
    }
}
 
Example 20
Source File: EmailMessageSender.java    From magic-starter with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 处理复杂邮件类型
 *
 * @param message 邮件内容
 * @return boolean
 */
private boolean processMimeEmail(EmailMessage message) {
	// 注意邮件发送可能出现异常,注意catch
	try {
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
		helper.setFrom("\"" + message.getFrom() + "\" <" + username + ">");
		helper.setTo(ArrayUtil.toArray(message.getTos(), String.class));
		helper.setSubject(message.getSubject());

		if (StrUtil.isNotBlank(message.getTemplate())) {
			// 使用模板生成邮件内容
			Context context = new Context();
			// 变量设置
			message.getParams().forEach(context::setVariable);
			String content = templateEngine.process(message.getTemplate(), context);

			helper.setText(content, true);
		} else {
			helper.setText(message.getContent(), true);
		}

		// 设置抄送人列表
		if (CollUtil.isEmpty(message.getCcs())) {
			helper.setCc(ArrayUtil.toArray(message.getCcs(), String.class));
		}

		// 设置附件
		if (CollUtil.isNotEmpty(message.getAttachments())) {
			for (EmailAttachment attachment : message.getAttachments()) {
				helper.addAttachment(attachment.getAttachmentName(), attachment.getAttachment());
			}
		}

		// 设置静态资源
		if (CollUtil.isNotEmpty(message.getStaticResources())) {
			for (EmailStaticResource staticResource : message.getStaticResources()) {
				helper.addInline(staticResource.getResourceId(), staticResource.getResource());
			}
		}

		mailSender.send(mimeMessage);
		return true;
	} catch (Exception e) {
		log.error("复杂邮件发送异常!", e);
		return false;
	}
}