Java Code Examples for javax.mail.internet.MimeMessage#setSentDate()
The following examples show how to use
javax.mail.internet.MimeMessage#setSentDate() .
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: MainAppExample.java From javamail with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws MessagingException { Properties javaMailConfiguration = new Properties(); javaMailConfiguration.put("mail.transport.protocol", "filetxt"); javaMailConfiguration.put("mail.files.path", "target/messages"); Session session = Session.getDefaultInstance(javaMailConfiguration); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); InternetAddress[] address = { new InternetAddress("[email protected]") }; message.setRecipients(Message.RecipientType.TO, address); Date now = new Date(); message.setSubject("JavaMail test at " + now); message.setSentDate(now); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("Body text version", "UTF-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<p>Body's text <strong>(html)</strong></p><p>Body html version</p>", "text/html; charset=UTF-8"); Multipart multiPart = new MimeMultipart("alternative"); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); session.getTransport().sendMessage(message, address); }
Example 2
Source File: MailSenderSMTP.java From rapidminer-studio with GNU Affero General Public License v3.0 | 6 votes |
@Override public void sendEmail(String address, String subject, String content, Map<String, String> headers, UnaryOperator<String> properties) throws Exception { Session session = MailUtilities.makeSession(properties); if (session == null) { LogService.getRoot().log(Level.WARNING, SESSION_CREATION_FAILURE, address); } MimeMessage msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, address); msg.setFrom(); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setText(content, "UTF-8"); if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { msg.setHeader(header.getKey(), header.getValue()); } } Transport.send(msg); }
Example 3
Source File: EmailSendTool.java From Lottery with GNU General Public License v2.0 | 6 votes |
/** * 此段代码用来发送普通电子邮件 * * @throws MessagingException * @throws UnsupportedEncodingException * @throws UnsupportedEncodingException */ public void send() throws MessagingException, UnsupportedEncodingException { Properties props = new Properties(); Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证 props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, auth); // 设置session,和邮件服务器进行通讯。 MimeMessage message = new MimeMessage(session); // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式 message.setSubject(mail_subject); // 设置邮件主题 message.setText(mail_body); // 设置邮件正文 message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题 message.setSentDate(new Date()); // 设置邮件发送日期 Address address = new InternetAddress(mail_from, personalName); message.setFrom(address); // 设置邮件发送者的地址 Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址 message.addRecipient(Message.RecipientType.TO, toAddress); Transport.send(message); // 发送邮件 }
Example 4
Source File: MailServerImpl.java From webcurator with Apache License 2.0 | 6 votes |
public void sendHTML(Mailable email) throws MessagingException { Session mailSession = Session.getInstance(this.mailConfig, null); MimeMessage message = new MimeMessage(mailSession); MimeMultipart multipart = new MimeMultipart("alternative"); BodyPart bp = new MimeBodyPart(); bp.setContent(email.getMessage(), "text/plain; charset=UTF-8"); BodyPart bp2 = new MimeBodyPart(); bp2.setContent(email.getMessage(), "text/html; charset=UTF-8"); multipart.addBodyPart(bp2); multipart.addBodyPart(bp); message.setContent(multipart); message.setSentDate(new java.util.Date()); message.setFrom(new InternetAddress(email.getSender())); message.setSubject(email.getSubject()); //FIXME if more than one recipient break it appart before setting the recipient field message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipients())); Transport.send(message); }
Example 5
Source File: DefaultClosableSmtpConnection.java From smtp-connection-pool with Apache License 2.0 | 6 votes |
private void doSend(MimeMessage mimeMessage, Address[] recipients) throws MessagingException { try { if (mimeMessage.getSentDate() == null) { mimeMessage.setSentDate(new Date()); } String messageId = mimeMessage.getMessageID(); mimeMessage.saveChanges(); if (messageId != null) { // Preserve explicitly specified message id... mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId); } delegate.sendMessage(mimeMessage, recipients); } catch (Exception e) { // TODO: An exception can be sent because the recipient is invalid, ie. not because the connection is invalid // TODO: Invalidate based on the MessagingException subclass / cause: IOException if (invalidateConnectionOnException) { invalidate(); } throw e; } }
Example 6
Source File: SmtpExecutor.java From BootNettyRpc with Apache License 2.0 | 6 votes |
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 ( cc != null && cc.length() != 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); } if (bcc != null && bcc.length() != 0) { 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 | 5 votes |
@Test public void javaMailSenderWithCustomSession() throws MessagingException { final Session session = Session.getInstance(new Properties()); MockJavaMailSender sender = new MockJavaMailSender() { @Override protected Transport getTransport(Session sess) throws NoSuchProviderException { assertEquals(session, sess); return super.getTransport(sess); } }; sender.setSession(session); sender.setHost("host"); sender.setUsername("username"); sender.setPassword("password"); MimeMessage mimeMessage = sender.createMimeMessage(); mimeMessage.setSubject("custom"); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime()); sender.send(mimeMessage); assertEquals("host", sender.transport.getConnectedHost()); assertEquals("username", sender.transport.getConnectedUsername()); assertEquals("password", sender.transport.getConnectedPassword()); assertTrue(sender.transport.isCloseCalled()); assertEquals(1, sender.transport.getSentMessages().size()); assertEquals(mimeMessage, sender.transport.getSentMessage(0)); }
Example 8
Source File: ImapServerTest.java From greenmail with Apache License 2.0 | 5 votes |
/** * Tests simple send and retrieve, including umlauts. * * @throws Exception on error. */ @Test public void testRetreiveSimple() throws Exception { assertNotNull(greenMail.getImap()); final String subject = GreenMailUtil.random() + UMLAUTS; final String body = GreenMailUtil.random() + "\r\n" + " öäü \u00c4 \u00e4" + "\r\n" + GreenMailUtil.random(); final String to = "test@localhost"; MimeMessage mimeMessage = new MimeMessage(greenMail.getSmtp().createSession()); mimeMessage.setSentDate(new Date()); mimeMessage.setFrom("from@localhost"); mimeMessage.setRecipients(Message.RecipientType.TO, to); mimeMessage.setSubject(subject, "UTF-8"); // Need to explicitly set encoding mimeMessage.setText(body, "UTF-8"); Transport.send(mimeMessage); greenMail.waitForIncomingEmail(5000, 1); try (Retriever retriever = new Retriever(greenMail.getImap())) { Message[] messages = retriever.getMessages(to); assertEquals(1, messages.length); assertEquals(subject, messages[0].getSubject()); assertEquals(body, ((String) messages[0].getContent()).trim()); } }
Example 9
Source File: GMailSender.java From vocefiscal-android with Apache License 2.0 | 5 votes |
public boolean send() throws Exception { Properties props = setProperties(); if(!user.equals("") && !pass.equals("") && to.length > 0 && !from.equals("") && !subject.equals("") && !body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] addressTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { addressTo[i] = new InternetAddress(to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); msg.setSubject(subject); msg.setSentDate(new Date()); // setup message body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); // Put parts in message msg.setContent(multipart); // send email Transport.send(msg); return true; } else { return false; } }
Example 10
Source File: SmtpManager.java From logging-log4j2 with Apache License 2.0 | 5 votes |
protected void sendMultipartMessage(final MimeMessage msg, final MimeMultipart mp) throws MessagingException { synchronized (msg) { msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); } }
Example 11
Source File: JavaMailSenderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void javaMailSenderWithCustomSession() throws MessagingException { final Session session = Session.getInstance(new Properties()); MockJavaMailSender sender = new MockJavaMailSender() { @Override protected Transport getTransport(Session sess) throws NoSuchProviderException { assertEquals(session, sess); return super.getTransport(sess); } }; sender.setSession(session); sender.setHost("host"); sender.setUsername("username"); sender.setPassword("password"); MimeMessage mimeMessage = sender.createMimeMessage(); mimeMessage.setSubject("custom"); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime()); sender.send(mimeMessage); assertEquals("host", sender.transport.getConnectedHost()); assertEquals("username", sender.transport.getConnectedUsername()); assertEquals("password", sender.transport.getConnectedPassword()); assertTrue(sender.transport.isCloseCalled()); assertEquals(1, sender.transport.getSentMessages().size()); assertEquals(mimeMessage, sender.transport.getSentMessage(0)); }
Example 12
Source File: EmailUtil.java From journaldev with MIT License | 5 votes |
/** * Utility method to send simple HTML email * @param session * @param toEmail * @param subject * @param body */ public static void sendEmail(Session session, String toEmail, String subject, String body){ 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("[email protected]", "NoReply-JD")); msg.setReplyTo(InternetAddress.parse("[email protected]", false)); msg.setSubject(subject, "UTF-8"); msg.setText(body, "UTF-8"); msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false)); System.out.println("Message is ready"); Transport.send(msg); System.out.println("EMail Sent Successfully!!"); } catch (Exception e) { e.printStackTrace(); } }
Example 13
Source File: AbstractIMAPRiverUnitTest.java From elasticsearch-imap with Apache License 2.0 | 4 votes |
protected void createInitialIMAPTestdata(final Properties props, final String user, final String password, final int count, final boolean deleteall) throws MessagingException { final Session session = Session.getInstance(props); final Store store = session.getStore(); store.connect(user, password); checkStoreForTestConnection(store); final Folder root = store.getDefaultFolder(); final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS"); final Folder testrootl2 = testroot.getFolder("Level(2!"); if (deleteall) { deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password); if (testroot.exists()) { testroot.delete(true); } final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS"); if (testrootenamed.exists()) { testrootenamed.delete(true); } } if (!testroot.exists()) { testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testroot.open(Folder.READ_WRITE); testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES); testrootl2.open(Folder.READ_WRITE); } final Folder inbox = root.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); final Message[] msgs = new Message[count]; for (int i = 0; i < count; i++) { final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL_TO)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS)); message.setSubject(EMAIL_SUBJECT + "::" + i); message.setText(EMAIL_TEXT + "::" + SID++); message.setSentDate(new Date()); msgs[i] = message; } inbox.appendMessages(msgs); testroot.appendMessages(msgs); testrootl2.appendMessages(msgs); IMAPUtils.close(inbox); IMAPUtils.close(testrootl2); IMAPUtils.close(testroot); IMAPUtils.close(store); }
Example 14
Source File: EwsExchangeSession.java From davmail with GNU General Public License v2.0 | 4 votes |
/** * Get item content. * * @param itemId EWS item id * @return item content as byte array * @throws IOException on error */ protected byte[] getContent(ItemId itemId) throws IOException { GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true); byte[] mimeContent = null; try { executeMethod(getItemMethod); mimeContent = getItemMethod.getMimeContent(); } catch (EWSException e) { LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage()); } if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new HttpNotFoundException("Item " + itemId + " not found"); } if (mimeContent == null) { LOGGER.warn("MimeContent not available, trying to rebuild from properties"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false); getItemMethod.addAdditionalProperty(Field.get("contentclass")); getItemMethod.addAdditionalProperty(Field.get("message-id")); getItemMethod.addAdditionalProperty(Field.get("from")); getItemMethod.addAdditionalProperty(Field.get("to")); getItemMethod.addAdditionalProperty(Field.get("cc")); getItemMethod.addAdditionalProperty(Field.get("subject")); getItemMethod.addAdditionalProperty(Field.get("date")); getItemMethod.addAdditionalProperty(Field.get("body")); executeMethod(getItemMethod); EWSMethod.Item item = getItemMethod.getResponseItem(); if (item == null) { throw new HttpNotFoundException("Item " + itemId + " not found"); } MimeMessage mimeMessage = new MimeMessage((Session) null); mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName())); mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName()))); mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName())); mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName())); mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName())); mimeMessage.setSubject(item.get(Field.get("subject").getResponseName())); String propertyValue = item.get(Field.get("body").getResponseName()); if (propertyValue == null) { propertyValue = ""; } mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8"); mimeMessage.writeTo(baos); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray(), StandardCharsets.UTF_8)); } mimeContent = baos.toByteArray(); } catch (IOException | MessagingException e2) { LOGGER.warn(e2); } if (mimeContent == null) { throw new IOException("GetItem returned null MimeContent"); } } return mimeContent; }
Example 15
Source File: SendMail.java From OA with GNU General Public License v3.0 | 4 votes |
public boolean send() { // 创建邮件Session所需的Properties对象.API建议使用set而不是put(putall). Properties props = new Properties(); props.setProperty("mail.smtp.host", smtpServer); props.setProperty("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "false"); props.put("mail.debug", "true"); // 创建Session对象,代表JavaMail中的一次邮件会话. // Authenticator==>Java mail的身份验证,如QQ邮箱是需要验证的.所以需要用户名,密码. // PasswordAuthentication==>系统的密码验证.内部类获取,或者干脆写个静态类也可以. Session session = Session.getDefaultInstance(props, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); try { // 构造MimeMessage并设置相关属性值,MimeMessage就是实际的电子邮件对象. MimeMessage msg = new MimeMessage(session); // 设置发件人 msg.setFrom(new InternetAddress(from)); // 设置收件人,为数组,可输入多个地址. InternetAddress[] addresses = { new InternetAddress(to) }; // Message.RecipientType==>TO(主要接收人),CC(抄送),BCC(密件抄送) msg.setRecipients(Message.RecipientType.TO, addresses); msg.setSentDate(new Date()); // 设置邮件主题,如果不是UTF-8就要转换下.MimeUtility.encodeText(subject,"gb2312","B")); // subject=translateChinese(subject); msg.setSubject(MimeUtility.encodeText(subject,"utf8","B")); // =====================正文部分=========== // 构造Multipart容器 Multipart mp = new MimeMultipart(); // =====================正文文字部分=========== // 向Multipart添加正文 MimeBodyPart mbpContent = new MimeBodyPart(); mbpContent.setContent(content,"text/plain;charset=gb2312"); // 将BodyPart添加到MultiPart容器中 mp.addBodyPart(mbpContent); // =====================正文附件部分=========== // 向MulitPart添加附件,遍历附件列表,将所有文件添加到邮件消息里 if (attachments != null) { for (String efile : attachments) { MimeBodyPart mbpFile = new MimeBodyPart(); // 以文件名创建FileDataSource对象 FileDataSource fds = new FileDataSource(efile); // 处理附件 mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); // 将BodyPart添加到Multipart容器中 mp.addBodyPart(mbpFile); } attachments.clear(); } // 向MimeMessage添加Multipart msg.setContent(mp); msg.setSentDate(new Date()); // 发送邮件,使用如下方法! Transport.send(msg); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example 16
Source File: SendMail.java From xunxian with Apache License 2.0 | 4 votes |
/** * * @param targetMail 发送至的账号 * @param title 发送的标题 * @param content 发送的内容 */ public void sendMail(String targetMail,String title,String content) { try { properties = new Properties(); //设置邮件服务器 properties.put("mail.smtp.host", "smtp.163.com"); //验证 properties.put("mail.smtp.auth", "true"); //根据属性新建一个邮件会话 mailSession = Session.getInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "cccccc"); } }); mailSession.setDebug(true); //建立消息对象 mailMessage = new MimeMessage(mailSession); //发件人 mailMessage.setFrom(new InternetAddress("[email protected]")); //收件人 mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(targetMail)); //主题 mailMessage.setSubject(title); //内容 mailMessage.setText(content); //发信时间 mailMessage.setSentDate(new Date()); //存储信息 mailMessage.saveChanges(); // trans = mailSession.getTransport("smtp"); //发送 trans.send(mailMessage); } catch (Exception e) { new File().log("邮件发送失败异常捕获:"+e.getMessage()); e.printStackTrace(); } finally { } }
Example 17
Source File: Mail.java From AccelerationAlert with Apache License 2.0 | 4 votes |
public boolean send() throws Exception { Properties props = _setProperties(); if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(_from)); InternetAddress[] addressTo = new InternetAddress[_to.length]; for (int i = 0; i < _to.length; i++) { addressTo[i] = new InternetAddress(_to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); msg.setSubject(_subject); msg.setSentDate(new Date()); // setup message body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(_body); _multipart.addBodyPart(messageBodyPart); // Put parts in message msg.setContent(_multipart); // send email Transport.send(msg); return true; } else { return false; } }
Example 18
Source File: ImapSearchTest.java From greenmail with Apache License 2.0 | 4 votes |
/** * Create the two messages with different recipients, etc. for testing and add them to the folder. * * @param session Session to set on the messages * @param folder Folder to add to * @param flags Flags to set on both messages */ private void storeSearchTestMessages(Session session, MailFolder folder, Flags flags) throws Exception { MimeMessage message0 = new MimeMessage(session); message0.setSubject("#0 test0Search"); message0.setText("content#0"); setRecipients(message0, Message.RecipientType.TO, "to", 1, 2); setRecipients(message0, Message.RecipientType.CC, "cc", 1, 2); setRecipients(message0, Message.RecipientType.BCC, "bcc", 1, 2); message0.setFrom(new InternetAddress("from2@localhost")); message0.setFlag(Flags.Flag.ANSWERED, true); message0.setFlags(flags, true); folder.store(message0); MimeMessage message1 = new MimeMessage(session); message1.setSubject("#1 test0Search test1Search \u00c4\u00e4\u03A0", "UTF-8"); message1.setText("content#1 \u00c4\u00e4\u03A0", "UTF-8"); setRecipients(message1, Message.RecipientType.TO, "to", 1, 3); setRecipients(message1, Message.RecipientType.CC, "cc", 1, 3); setRecipients(message1, Message.RecipientType.BCC, "bcc", 1, 3); message1.setFrom(new InternetAddress("from3@localhost")); message1.setFlag(Flags.Flag.ANSWERED, false); folder.store(message1); MimeMessage message2 = new MimeMessage(session); message2.setSubject("#2 OR search : foo"); message2.setText("content#2 foo"); setRecipients(message2, Message.RecipientType.TO, "to", 3); setRecipients(message2, Message.RecipientType.CC, "cc", 4); setRecipients(message2, Message.RecipientType.BCC, "bcc", 5); message2.setFrom(new InternetAddress("from4@localhost")); message2.setFlag(Flags.Flag.ANSWERED, false); message2.setFlags(flags, false); folder.store(message2); MimeMessage message3 = new MimeMessage(session); message3.setSubject("#3 OR search : bar"); message3.setText("content#3 bar"); setRecipients(message3, Message.RecipientType.TO, "to", 3); setRecipients(message3, Message.RecipientType.CC, "cc", 4); setRecipients(message3, Message.RecipientType.BCC, "bcc", 5); message3.setFrom(new InternetAddress("from5@localhost")); message3.setFlag(Flags.Flag.ANSWERED, false); message3.setFlags(flags, false); folder.store(message3); MimeMessage message4 = new MimeMessage(session); message4.setSubject("#4 with received date"); message4.setText("content#4 received date"); folder.appendMessage(message4, new Flags(), getSampleDate()); MimeMessage message5 = new MimeMessage(session); message5.setSubject("#5 with sent date"); message5.setText("content#5 sent date"); message5.setSentDate(getSampleDate()); folder.store(message5); }
Example 19
Source File: SignAdminAction.java From Login-System-SSM with MIT License | 4 votes |
@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 }
Example 20
Source File: MailManager.java From entando-components with GNU Lesser General Public License v3.0 | 3 votes |
/** * Prepare a MimeMessage complete of sender, recipient addresses, subject * and current date but lacking in the message text content. * @param session The session object. * @param subject The e-mail subject. * @param recipientsTo The e-mail main destination addresses. * @param recipientsCc The e-mail 'carbon-copy' destination addresses. * @param recipientsBcc The e-mail 'blind carbon-copy' destination addresses. * @param senderCode The sender code, as configured in the service configuration. * @return A mime message without message text content. * @throws AddressException In case of non-valid e-mail addresses. * @throws MessagingException In case of errors preparing the mail message. */ protected MimeMessage prepareVoidMimeMessage(Session session, String subject, String[] recipientsTo, String[] recipientsCc, String[] recipientsBcc, String senderCode) throws AddressException, MessagingException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(this.getConfig().getSender(senderCode))); msg.setSubject(subject); msg.setSentDate(new Date()); this.addRecipients(msg, Message.RecipientType.TO, recipientsTo); this.addRecipients(msg, Message.RecipientType.CC, recipientsCc); this.addRecipients(msg, Message.RecipientType.BCC, recipientsBcc); msg.saveChanges(); return msg; }