Java Code Examples for javax.mail.internet.MimeMessage#setFrom()

The following examples show how to use javax.mail.internet.MimeMessage#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: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
Example 2
Source File: Postman.java    From web-budget with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Listen for e-mail requests through CDI events and send the message
 * 
 * @param mailMessage the message to send
 * @throws Exception if any problem occur in the process
 */
public void send(@Observes MailMessage mailMessage) throws Exception {
   
    final MimeMessage message = new MimeMessage(this.mailSession);

    // message header
    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());
    
    // message body
    message.setText(mailMessage.getContent(), "UTF-8", "html");
    message.setSentDate(new Date());

    // send
    Transport.send(message);
}
 
Example 3
Source File: MailConnection.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
protected MimeMessage format(Reader reader, PropertiesSubstitutor ps) throws MessagingException, IOException {
    //Read message body content
    String text = ps.substitute(reader);
    //Create message and set headers
    MimeMessage message = new MimeMessage(session);

    message.setFrom(InternetAddress.getLocalAddress(session));

    if (subject != null) {
        message.setSubject(ps.substitute(subject));
    }
    //if html content
    if (TYPE_HTML.equalsIgnoreCase(type)) {
        BodyPart body = new MimeBodyPart();
        body.setContent(text, "text/html");
        Multipart mp = new MimeMultipart("related");
        mp.addBodyPart(body);
        message.setContent(mp);
    } else {
        message.setText(text);
    }
    return message;
}
 
Example 4
Source File: MailServiceTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Test
public void testJavaxTransportSendAndReceiveBasicMessage() throws Exception {
    assumeEnvironment(Environment.APPSPOT, Environment.CAPEDWARF);

    Session session = instance(Session.class);
    if (session == null) {
        session = Session.getDefaultInstance(new Properties(), null);
    }
    MimeProperties mp = new MimeProperties();
    mp.subject = "Javax-Transport-Test-" + System.currentTimeMillis();
    mp.from = getEmail("from-test-x", EmailMessageField.FROM);
    mp.to = getEmail("to-test-x", EmailMessageField.TO);
    mp.body = BODY;

    MimeMessage msg = new MimeMessage(session);
    msg.setSubject(mp.subject);
    msg.setFrom(new InternetAddress(mp.from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mp.to));
    msg.setText(BODY);
    // Send email to self for debugging.
    // msg.setRecipient(Message.RecipientType.CC, new InternetAddress("[email protected]"));

    Transport.send(msg);

    assertMessageReceived(mp);
}
 
Example 5
Source File: JavamailService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
Example 6
Source File: SmtpExecutor.java    From Thunder with Apache License 2.0 6 votes vote down vote up
/**
 * 发送邮件
 * @param from      发送者地址
 * @param to        接受者地址,可以多个,用逗号隔开
 * @param cc        抄送者地址,可以多个,用逗号隔开
 * @param bcc       暗抄送者地址,可以多个,用逗号隔开
 * @param subject   邮件主体
 * @param text      邮件内容,支持Html格式
 * @param htmlStyle 邮件内容,支持Html格式
 * @param encoding  编码
 * @throws Exception 异常抛出
 */
public void send(String from, String to, String cc, String bcc, String subject, String text, boolean htmlStyle, String encoding) throws Exception {
    MimeMessage message = new MimeMessage(session);

    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    if (StringUtils.isNotEmpty(cc)) {
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
    }
    if (StringUtils.isNotEmpty(bcc)) {
        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
    }
    message.setSubject(subject);
    if (htmlStyle) {
        message.setContent(text, "text/html;charset=" + encoding);
    } else {
        message.setText(text);
    }

    Transport.send(message);
}
 
Example 7
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
	MockJavaMailSender sender = new MockJavaMailSender();
	MimeMessagePreparator preparator = new MimeMessagePreparator() {
		@Override
		public void prepare(MimeMessage mimeMessage) throws MessagingException {
			mimeMessage.setFrom(new InternetAddress(""));
		}
	};
	try {
		sender.send(preparator);
	}
	catch (MailParseException ex) {
		// expected
		assertTrue(ex.getCause() instanceof AddressException);
	}
}
 
Example 8
Source File: JamesMailetContext.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a bounce mail that is a bounce of the original message.
 *
 * @param bounceText the text to be prepended to the message to describe the bounce
 *                   condition
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException {
    Preconditions.checkArgument(mail.hasSender(), "Mail should have a sender");
    // This sends a message to the james component that is a bounce of the sent message
    MimeMessage original = mail.getMessage();
    MimeMessage reply = (MimeMessage) original.reply(false);
    reply.setSubject("Re: " + original.getSubject());
    reply.setSentDate(new Date());
    Collection<MailAddress> recipients = mail.getMaybeSender().asList();
    MailAddress sender = mail.getMaybeSender().get();

    reply.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getMaybeSender().asString()));
    reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
    reply.setText(bounceText);
    reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName());
    return MailImpl.builder()
        .name("replyTo-" + mail.getName())
        .sender(sender)
        .addRecipients(recipients)
        .mimeMessage(reply)
        .build();
}
 
Example 9
Source File: SendingMailService.java    From email-verification-springboot-mysql-nginx-dockercompose with MIT License 5 votes vote down vote up
private boolean sendMail(String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        Transport transport = session.getTransport();
        transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
        transport.sendMessage(msg, msg.getAllRecipients());
        return true;
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }

    return false;
}
 
Example 10
Source File: EmailServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
private Message prepareMessage(EmailConfig email) throws UnsupportedEncodingException,
    MessagingException {

  Properties props = new Properties();
  Session session = Session.getDefaultInstance(props, null);
  MimeMessage msg = new MimeMessage(session);
  msg.setFrom(getFrom());
  for (String to : email.getTo()) {
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  }
  msg.setContent(email.getBody(), "text/html");
  msg.setSubject(email.getSubject(), "UTF-8");
  return msg;
}
 
Example 11
Source File: SendEmail.java    From Hybrid-Music-Recommender-System with MIT License 5 votes vote down vote up
private static MimeMessage createSimpleMail(Session session, String theme, String messages,String email) throws Exception {
	MimeMessage message = new MimeMessage(session);
	message.setFrom(new InternetAddress("[email protected]"));
	message.addRecipients(Message.RecipientType.TO, email);
	message.setSubject(theme);
	message.setText(messages);
	message.saveChanges();
	return message;
}
 
Example 12
Source File: EMailUtil.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method to send simple HTML email
 */
private void sendEmail() {

  Logger logger = Logger.getLogger("Mail Error");
  try {
    MimeMessage msg = new MimeMessage(session);
    // set message headers
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(toEmail, "MZmine"));

    msg.setSubject(subject, "UTF-8");

    msg.setText("MZmine 2 has detected an error :\n" + body, "UTF-8");

    msg.setSentDate(new Date());

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

    Transport.send(msg);

    logger.info("Successfully sended error mail: " + subject + "\n" + body);
  } catch (Exception e) {
    logger.info("Failed sending error mail:" + subject + "\n" + body);
    e.printStackTrace();
  }
}
 
Example 13
Source File: POP3TestCase.java    From javamail-mock2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = MockTestException.class)
public void testOnlyInbox() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore(Providers.getPOP3Provider("makes_no_differernce", false, true));
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();

    try {
        defaultFolder.getFolder("test");
    } catch (final MessagingException e) {
        throw new MockTestException(e);
    }

}
 
Example 14
Source File: EMailUtil.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method to send simple HTML email
 */
private void sendEmail() {

  Logger logger = Logger.getLogger("Mail Error");
  try {
    MimeMessage msg = new MimeMessage(session);
    // set message headers
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(toEmail, "MZmine"));

    msg.setSubject(subject, "UTF-8");

    msg.setText("MZmine has detected an error :\n" + body, "UTF-8");

    msg.setSentDate(new Date());

    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

    Transport.send(msg);

    logger.info("Successfully sended error mail: " + subject + "\n" + body);
  } catch (Exception e) {
    logger.info("Failed sending error mail:" + subject + "\n" + body);
    e.printStackTrace();
  }
}
 
Example 15
Source File: MailingListPublisher.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Publish post.
 *
 * @throws MessagingException if an error occurs while publishing.
 * @throws IOException if there are problems with reading file with the post text.
 */
public void publish() throws MessagingException, IOException {
    final Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", SMTP_HOST);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.auth", true);

    final Session session = Session.getInstance(props, null);
    final MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.addRecipients(Message.RecipientType.TO,
            InternetAddress.parse(RECIPIENT_ADDRESS));

    final String post = new String(Files.readAllBytes(Paths.get(postFilename)),
            StandardCharsets.UTF_8);

    final BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(post, "text/plain");

    final Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);

    final Transport transport = session.getTransport("smtp");
    transport.connect(SMTP_HOST, username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
 
Example 16
Source File: SMTPNotifier.java    From juddi with Apache License 2.0 5 votes vote down vote up
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException {

		

		try {
                        log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
			if (session !=null && notificationEmailAddress != null) {
				MimeMessage message = new MimeMessage(session);
				InternetAddress address = new InternetAddress(notificationEmailAddress);
				Address[] to = {address};
				message.setRecipients(RecipientType.TO, to);
				message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
				//maybe nice to use a template rather then sending raw xml.
				String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES);
				message.setText(subscriptionResultXML, "UTF-8");
                                //message.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
				message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.default.subject") + " " 
						+ StringEscapeUtils.escapeHtml(body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()));
				Transport.send(message);
			}
                        else throw new DispositionReportFaultMessage("Session is null!", null);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw new DispositionReportFaultMessage(e.getMessage(), null);
		}

		DispositionReport dr = new DispositionReport();
		Result res = new Result();
		dr.getResult().add(res);

		return dr;
	}
 
Example 17
Source File: SendMessage.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void send(SesClient client,
                        String sender,
                        String recipient,
                        String subject,
                        String bodyText,
                        String bodyHTML
) throws AddressException, MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());

    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Add subject, from and to lines.
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

    // Create a multipart/alternative child container.
    MimeMultipart msgBody = new MimeMultipart("alternative");

    // Create a wrapper for the HTML and text parts.
    MimeBodyPart wrap = new MimeBodyPart();

    // Define the text part.
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");

    // Define the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");

    // Add the text and HTML parts to the child container.
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);

    // Add the child container to the wrapper object.
    wrap.setContent(msgBody);

    // Create a multipart/mixed parent container.
    MimeMultipart msg = new MimeMultipart("mixed");

    // Add the parent container to the message.
    message.setContent(msg);

    // Add the multipart/alternative part to the message.
    msg.addBodyPart(wrap);

    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);

        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);

        SdkBytes data = SdkBytes.fromByteArray(arr);

        RawMessage rawMessage = RawMessage.builder()
                .data(data)
                .build();

        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                .rawMessage(rawMessage)
                .build();

        client.sendRawEmail(rawEmailRequest);

    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }


}
 
Example 18
Source File: EmailUtils.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sends an email to a given recipient for a given subject and content
 * with a {@code reply-to} header.
 *
 * @param to      The recipient of the mail ({@code to} header).
 * @param subject The subject of the mail.
 * @param text    The content of the mail.
 * @param replyTo The {@code reply-to} email header.
 * @return {@code true} if successful, {@code false} otherwise.
 */
private static boolean sendEmail(String to, String subject, String text, String replyTo) {
    final boolean emailEnabled = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAILS_ENABLED).getBoolValue();
    if (!emailEnabled) {
        logger.error("Tried to send a mail, but sending emails is disabled. Update your system settings.");
        return false;
    }

    final String smtpHost = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_HOST).getStringValue();
    final int smtpPort = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_PORT).getIntValue();
    final String emailAddress = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_ADDRESS).getStringValue();
    final String emailPassword = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_PASSWORD).getStringValue();
    final boolean debug = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.DEBUG_MODE).getBoolValue();

    try    {
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailAddress, emailPassword);
            }});

        session.setDebug(debug);
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(emailAddress));
        msg.setReplyTo(InternetAddress.parse(replyTo));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        msg.setSubject(subject);
        msg.setContent(text, "text/plain");
        msg.setSentDate(new Date());

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, smtpPort, emailAddress, emailPassword);
        Transport.send(msg);
        transport.close();

        logger.info(String.format("Mail sent: to: %s, replyTo: %s", to, replyTo));
    } catch (MessagingException messagingException) {
        logger.warn("Failed to send email.", messagingException);
        return false;
    }
    return true;
}
 
Example 19
Source File: SendAttachmentMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    prop.setProperty("mail.debug", "true");
    prop.setProperty("mail.host", MAIL_SERVER_HOST);
    prop.setProperty("mail.transport.protocol", "smtp");
    prop.setProperty("mail.smtp.auth", "true");

    // 1、创建session
    Session session = Session.getInstance(prop);

    // 2、通过session得到transport对象
    Transport ts = session.getTransport();

    // 3、连上邮件服务器
    ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

    // 4、创建邮件
    MimeMessage message = new MimeMessage(session);

    // 邮件消息头
    message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
    message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
    message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
    message.setSubject("测试带附件邮件"); // 邮件的标题

    MimeBodyPart text = new MimeBodyPart();
    text.setContent("邮件中有两个附件。", "text/html;charset=UTF-8");

    // 描述数据关系
    MimeMultipart mm = new MimeMultipart();
    mm.setSubType("related");
    mm.addBodyPart(text);
    String[] files = { "D:\\00_Temp\\temp\\1.jpg", "D:\\00_Temp\\temp\\2.png" };

    // 添加邮件附件
    for (String filename : files) {
        MimeBodyPart attachPart = new MimeBodyPart();
        attachPart.attachFile(filename);
        mm.addBodyPart(attachPart);
    }

    message.setContent(mm);
    message.saveChanges();

    // 5、发送邮件
    ts.sendMessage(message, message.getAllRecipients());
    ts.close();
}
 
Example 20
Source File: SignAdminAction.java    From Login-System-SSM with MIT License 4 votes vote down vote up
@Override
	protected ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object object, BindException exception)
			throws Exception {
		Admin admin = (Admin) object;  //将数据封装起来
System.out.println("表单提交过来时的数据是:"+admin.toString());

			if (adminService.addAdmin(admin)) {    //调用该方法,将数据持久到数据库中,如果持久化成功,则发送邮件给当前的注册用户
				try {
					String host = "smtp.qq.com"; // 邮件服务器
					String from = "[email protected]"; // 发送邮件的QQ
					String authcode = "fgoobvssrkuibjhe"; // 对于QQ的个人邮箱而言,密码使用的是客户端的授权码,而不是用户的邮箱密码
					Properties props = System.getProperties();
					props.put("mail.smtp.host", host);
					props.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议名称
					props.put("mail.smtp.auth", "true"); // 开启授权
					props.put("mail.smtp.user", from);
					props.put("mail.smtp.password", authcode);
					props.put("mail.smtp.port", "587"); // smtp邮件服务器的端口号,必须是587,465端口调试时失败
					props.setProperty("mail.smtp.ssl.enable", "true");

					Session session = Session.getDefaultInstance(props,
							new GMailAuthenticator("[email protected]",
									"fgoobvssrkuibjhe"));

					props.put("mail.debug", "true");

					MimeMessage message = new MimeMessage(session);
					Address fromAddress = new InternetAddress(from);
					Address toAddress = new InternetAddress(admin.getEmail());

					message.setFrom(fromAddress);
					message.setRecipient(Message.RecipientType.TO, toAddress);

					message.setSubject("注册成功确认邮件");
					message.setSentDate(new Date());
					//发送的链接包括其写入到数据库中的UUID,也就是链接localhost:8080/Login_Sys/ActivateServlet和UUID的拼接,#连接两个字符串
					//获取UUID
System.out.println(adminService.getUUID(admin));
					message.setContent("<h1>恭喜你注册成功,请点击下面的连接激活账户</h1><h3><a href='http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate.action?code="+adminService.getUUID(admin)+"'>http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate</a></h3>","text/html;charset=utf-8");
					Transport transport = session.getTransport();
					transport.connect(host, from, authcode);
					message.saveChanges();
					Transport.send(message);
					transport.close();

				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}

			} 
	    
//封装一个ModelAndView对象,提供转发视图的功能
	    ModelAndView modelAndView = new ModelAndView();
	    modelAndView.addObject("message", "增加管理员成功");
	    modelAndView.setViewName("sign_success");      //成功之后跳转到该界面,采用逻辑视图,必须要配置视图解析器
		return modelAndView;  //该方法一定要返回modelAndView
	}