public static void main(String[] args) { String to = "*****@*****.**"; // change accordingly String from = "*****@*****.**"; // change accordingly String host = "smtp.gmail.com"; // or IP address // Get the session object Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); // compose the message try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Ping"); message.setText("Hello, this is example of sending email "); // Send message Transport.send(message); System.out.println("message sent successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
// 关闭连接 public void closeConnect() { try { if (folder != null) folder.close(true); // 关闭连接时是否删除邮件,true删除邮件 } catch (MessagingException e) { e.printStackTrace(); } finally { try { if (store != null) store.close(); // 关闭收件箱连接 } catch (MessagingException e) { e.printStackTrace(); } } }
public static Renderable[] getMessages( String emailServer, String user, String password, String provider) { Store store = null; Folder inboxfolder = null; Renderable[] renderedMsgs = null; try { store = getEmailStore(emailServer, user, password, provider); inboxfolder = getMailInbox(store); Calendar date = Calendar.getInstance(); date.add(Calendar.HOUR, -10); SearchTerm newer = new SentDateTerm(ComparisonTerm.GE, date.getTime()); try { Message[] msg = inboxfolder.search(newer, inboxfolder.getMessages()); if (msg != null) { renderedMsgs = new Renderable[msg.length]; } else { return null; } for (int j = msg.length - 1; j >= 0; j--) { renderedMsgs[j] = getMessage(msg[j]); } } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* for(int j=msgs.length-1;j>=0;j--) { }*/ } finally { try { inboxfolder.close(false); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { store.close(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return renderedMsgs; }
/** Sends a list of reservations in one message. */ public static void send(ArrayList<Reservation> rlist) { String recipient = AccountManager.getEmail(rlist.get(0).name); if (recipient == null) return; String msg = "The administrator has removed the following reservation(s):\n"; for (Reservation r : rlist) msg += formatReservation(r) + "\n"; msg += "\nFor help with using the computer reservation tool, send an email to " + "*****@*****.**"; try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(email)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject("Your computer reservation(s) have been removed"); message.setText(msg); Transport.send(message); Server.println("Email sent to " + recipient); } catch (MessagingException e) { e.printStackTrace(); } }
public boolean send() { try { MimeMessage msg = javaMailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8"); message.setFrom(from); message.setSubject(title); message.setTo(toEmails); message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数�� // message.addInline("myLogo",new ClassPathResource("img/mylogo.gif")); // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf")); javaMailSender.send(msg); } catch (MessagingException e) { e.printStackTrace(); if (log.isWarnEnabled()) { log.warn("邮件信息导常! 邮件标题为: " + title); } return false; } catch (MailException me) { me.printStackTrace(); if (log.isWarnEnabled()) { log.warn("发送邮件失败! 邮件标题为: " + title); } return false; } return true; }
@Test public void testByteArrayToSMIME() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); TEST_CASE1.writeTo(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ByteArraytoSMIME transformer = new ByteArraytoSMIME(); Object object = transformer.transformMimeMessage(in, null); assertNotNull(object); assertTrue(object instanceof MimeMultipart); MimeMultipart mime = (MimeMultipart) object; assertEquals(TEST_CASE1.getBodyPart(0).getContent(), mime.getBodyPart(0).getContent()); assertEquals(TEST_CASE1.getBodyPart(1).getContent(), mime.getBodyPart(1).getContent()); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } }
/** * Este método é responsável por enviar email. * * @param pServidorSMTP * @param pDe * @param pPara * @param pCopia * @param pBcc * @param pAssunto * @param pTexto * @return true se o email for enviado, false caso contrário. */ public static boolean enviarEmail( final String pServidorSMTP, final String pDe, final String pPara, final String pCopia, final String pBcc, final String pAssunto, final String pTexto) { Properties mailPprops = new Properties(); mailPprops.put("mail.smtp.host", pServidorSMTP); Session mailSession = Session.getDefaultInstance(mailPprops, null); try { // Mudança: Aplicação usa ";", componente usa "," String para = pPara.replaceAll(";", ","); // Criando a mensagem MimeMessage msg = new MimeMessage(mailSession); // Atribuir rementente msg.setFrom(new InternetAddress(pDe)); // Atribuir destinatários InternetAddress[] endereco = null; // Para if ((para != null) && (!para.equals(""))) { endereco = InternetAddress.parse(para); msg.setRecipients(Message.RecipientType.TO, endereco); } // Cc if ((pCopia != null) && (!pCopia.equals(""))) { endereco = InternetAddress.parse(pCopia); msg.setRecipients(Message.RecipientType.CC, endereco); } // Bcc if ((pBcc != null) && (!pBcc.equals(""))) { endereco = InternetAddress.parse(pBcc); msg.setRecipients(Message.RecipientType.BCC, endereco); } // Atribuir assunto msg.setSubject(pAssunto); // Atribuir corpo do email (texto) if (pTexto != null) msg.setContent(pTexto, "text/html"); msg.setSentDate(new Date()); Transport.send(msg); msg = null; mailSession = null; } catch (MessagingException mex) { if (Constants.DEBUG) { mex.printStackTrace(System.out); } return false; } return true; }
public void mail(String toAddress, String subject, String body) { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.ssl.enable", true); Authenticator authenticator = null; if (login) { props.put("mail.smtp.auth", true); authenticator = new Authenticator() { private PasswordAuthentication pa = new PasswordAuthentication(username, password); @Override public PasswordAuthentication getPasswordAuthentication() { return pa; } }; } Session s = Session.getInstance(props, authenticator); s.setDebug(debug); MimeMessage email = new MimeMessage(s); try { email.setFrom(new InternetAddress(from)); email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); email.setSubject(subject); email.setSentDate(new Date()); email.setText(body); Transport.send(email); } catch (MessagingException ex) { ex.printStackTrace(); } }
private void setTextArea() { String date = ""; String from = ""; String to = ""; to = removeFirstSpace(messageHandler.getToText()); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/YYYY hh:mm a"); date = simpleDateFormat.format(message.getSentDate()); from = getFrom(); } catch (MessagingException e) { e.printStackTrace(); } referenceTextArea = textArea; textArea.setText( "\n\n\n" + ">Date: " + date + "\n" + ">From: " + from + "\n>To: " + to + "\n>" + messageHandler.getText()); textArea.setCaretPosition(0); }
public FolderTableModel() { try { setFolder(null); } catch (MessagingException ex) { ex.printStackTrace(); } }
private static Folder getMailInbox(Store store) { Folder folder = null; Folder inboxfolder = null; try { folder = store.getDefaultFolder(); if (folder == null) throw new Exception("No default folder"); inboxfolder = folder.getFolder("INBOX"); if (inboxfolder == null) throw new Exception("No INBOX"); inboxfolder.open(Folder.READ_ONLY); Message[] msgs = inboxfolder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add("Subject"); inboxfolder.fetch(msgs, fp); return inboxfolder; } catch (NoSuchProviderException ex) { ex.printStackTrace(); } catch (MessagingException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { } return null; }
/** * 以文本格式发送邮件 * * @param mailInfo 待发送的邮件信息 */ public static boolean sendTextMail(MailSenderInfo mailInfo) { // 判断是否需要身份认证 MailAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; }
public boolean send() { Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(from); toAddress = new InternetAddress(to); } catch (AddressException e) { e.printStackTrace(); return false; } try { simpleMessage.setFrom(fromAddress); simpleMessage.setRecipient(RecipientType.TO, toAddress); simpleMessage.setSubject(subject); simpleMessage.setText(text); Transport.send(simpleMessage); return true; } catch (MessagingException e) { e.printStackTrace(); return false; } }
protected void loadChildren() { try { // connect to the Store if we need to if (!store.isConnected()) { store.connect(); } // get the default folder, and list the // subscribed folders on it folder = store.getDefaultFolder(); // Folder[] sub = folder.listSubscribed(); Folder[] sub = folder.list(); // add a FolderTreeNode for each Folder int num = sub.length; for (int i = 0; i < num; i++) { FolderTreeNode node = new FolderTreeNode(sub[i]); // we used insert here, since add() would make // another recursive call to getChildCount(); insert(node, i); } } catch (MessagingException me) { me.printStackTrace(); } }
public static boolean sendEmail(String email, String text, String subject) { final String username = "******"; final String password = "******"; try { Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.port", "587"); Session session = Session.getInstance( prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(username)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); msg.setSubject(subject); msg.setText(text); Transport.send(msg); return true; } catch (MessagingException me) { me.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } return false; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); Properties pros = System.getProperties(); pros.setProperty("mail.smtp.host", "localhost"); Session mailsession = Session.getDefaultInstance(properties); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String to = email; String from = "*****@*****.**"; // enter the senders email String subject = ""; // enter a subject String body = ""; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); msg.setText(body); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } }
private int execute(String[] args) { if (args.length != 1) { System.err.println("Usage: EmailNotifier path-to-property-file"); return -1; } File f = new File(args[0]); FileInputStream in; try { in = new FileInputStream(f); } catch (FileNotFoundException e) { System.err.println("Property file not found:" + f.getAbsolutePath()); return -2; } Properties props = new Properties(); try { props.load(in); } catch (IOException e) { System.err.println("Can not read from property file."); return -3; } try { sendMail(props); } catch (MessagingException e) { System.err.println("Failed to send mail."); e.printStackTrace(); return -4; } return 0; }
public void SendEmail(String email, String contestToken) { String to = email; String from = "Tyumen_ACM_Society"; String host = "smtp.gmail.com"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); props.put("mail.stmp.user", "*****@*****.**"); props.put("mail.smtp.password", "475508th"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props, new SmtpAuthenticator()); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Registration on acm.utmn.ru"); message.setText( "Hello! Thank you for registration on acm.utmn.ru! Use next token to submit tasks: " + contestToken); Transport t = session.getTransport("smtp"); t.send(message); System.out.println("Message was successfully sent."); } catch (MessagingException mex) { mex.printStackTrace(); } }
/** * sendSellAlert 売った方が良いレートになった場合のアラートを送信する。 * * @param addr * @param ttb * @param tts */ public static void sendSellAlert(String addr, String ttb, String tts, String currency) { // for debug Logger logger = Logger.getLogger("Mail"); logger.warning("sendSellAlert " + addr); StringBuffer sb = new StringBuffer(); // メール送信 Properties props = new Properties(); // ここからローカルデバッグ用 props.put("mail.smtp.host", "smtp.nifty.com"); // ここまで Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(MY_FROM_ADDRESS)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(addr)); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); sb.append(e.getMessage()); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); sb.append(e.getMessage()); } try { msg.setSubject("Sell " + currency + "!"); msg.setText(currency + " 売れ!" + tts + "\n" + "買値 = " + ttb); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); sb.append(e.getMessage()); } try { logger.warning("sb = " + sb.toString()); Transport.send(msg); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); sb.append(e.getMessage()); } logger.warning("e.getMessage = " + sb.toString()); }
public void sendOTPToEmail(String to, String subject, String Username, String Password) { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); switch (protocol) { case SMTPS: props.put("mail.smtp.ssl.enable", true); break; case TLS: props.put("mail.smtp.starttls.enable", true); break; } Authenticator authenticator = null; if (auth) { props.put("mail.smtp.auth", true); authenticator = new Authenticator() { private PasswordAuthentication pa = new PasswordAuthentication(username, password); @Override public PasswordAuthentication getPasswordAuthentication() { return pa; } }; } Session session = Session.getInstance(props, authenticator); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] address = {new InternetAddress(to)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject); message.setSentDate(new Date()); /* message.setText(body); */ Multipart multipart = new MimeMultipart("alternative"); MimeBodyPart textPart = new MimeBodyPart(); // If email client does not support html------------------------- String textContent = "Username: "******" Password:"******"<html><h1>QCollect " + "</h1><p><h3>Please Use the following OTP to login to your Account</h3></p>" + Password + "</p></html>"; htmlPart.setContent(htmlContent, "text/html"); multipart.addBodyPart(textPart); multipart.addBodyPart(htmlPart); message.setContent(multipart); Transport.send(message); } catch (MessagingException ex) { ex.printStackTrace(); } }
public void sendMail(String From, String To, String subject, String body) { Properties props = new Properties(); props.put("mail.smtp.user", "*****@*****.**"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", " javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance( props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("*****@*****.**", "password"); } }); // // session.setDebug(true); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(From)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To)); message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtps"); transport.connect( "smtp.gmail.com", Integer.valueOf(465), "*****@*****.**", "password;"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); // System.out.println("Done"); // } catch (MessagingException e) { } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { throw new RuntimeException(e.toString()); } }
public static void closeStore(Store store) { if (store == null) return; try { store.close(); } catch (MessagingException ex) { ex.printStackTrace(); // nop } }
@Override public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception { if (askGmailPassword || gmailPassword == null || gmailUsername == null) { Pair<String, String> credentials = GuiUtils.askCredentials( ConfigFetch.getSuperParentFrame(), "Enter Gmail Credentials", getGmailUsername(), getGmailPassword()); if (credentials == null) return null; setGmailUsername(credentials.first()); setGmailPassword(credentials.second()); PluginUtils.saveProperties("conf/rockblock.props", this); askGmailPassword = false; } Properties props = new Properties(); props.put("mail.store.protocol", "imaps"); ArrayList<IridiumMessage> messages = new ArrayList<>(); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword()); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); int numMsgs = inbox.getMessageCount(); for (int i = numMsgs; i > 0; i--) { Message m = inbox.getMessage(i); if (m.getReceivedDate().before(timeSince)) { break; } else { MimeMultipart mime = (MimeMultipart) m.getContent(); for (int j = 0; j < mime.getCount(); j++) { BodyPart p = mime.getBodyPart(j); Matcher matcher = pattern.matcher(p.getContentType()); if (matcher.matches()) { InputStream stream = (InputStream) p.getContent(); byte[] data = IOUtils.toByteArray(stream); IridiumMessage msg = process(data, matcher.group(1)); if (msg != null) messages.add(msg); } } } } } catch (NoSuchProviderException ex) { ex.printStackTrace(); System.exit(1); } catch (MessagingException ex) { ex.printStackTrace(); System.exit(2); } return messages; }
protected void injectMailHeader(MimeMessage mm) { for (Object name : mailHeaders.keySet()) { try { mm.setHeader((String) name, mailHeaders.getProperty((String) name)); } catch (MessagingException e) { e.printStackTrace(); } } }
@Override protected void updateMessageID() { try { setHeader("Message-ID", savedMessageId); } catch (javax.mail.MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/* * Writes/Sends an Email */ public void writeConfirmationEmail( String firstName, String lastName, String username, String password, String email) { String to = email; String from = "*****@*****.**"; String host = "smtp.ilstu.edu"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.user", "cssumne"); // if needed properties.setProperty("mail.password", "stuC0rb!"); // if needed Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Profile Created!"); String htmlText = "<h1>Congratulations, " + firstName + " " + lastName + "! Your Profile has been created!</h1>" + "<img src=\"cid:image\">" + "<p>Username: "******"</p>" + "<p>Email: " + email + "</p>" + "<p>Password: "******"</p>" + "<p>Thank You for Joining!</p>"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds; fds = new FileDataSource( "C:\\Users\\Corbin\\Desktop\\Github\\WebDevSemesterProject\\SilentAuction\\web\\resources\\bf_logo.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
/** * 发送邮件不带附件 * * @author bxmen * @param user 用户名 * @param password 密码 * @param smtpHost 邮件服务器 * @param userName 发件人姓名 * @param toAddr 接收者 * @param subject 邮件主题 * @param body 邮件内容 * @summary */ public void send( String user, String password, String smtpHost, String userName, String toAddr, String subject, String body) { try { Authenticator auth = new MailAuthenticator(user, password); Properties props = new Properties(); // 指定SMTP服务器,邮件通过它来投递 props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, auth); Message msg = new MimeMessage(session); // 指定发信人中文名称 if (null != userName && !userName.trim().equals("")) { msg.setFrom(new InternetAddress(user, userName)); } else { msg.setFrom(new InternetAddress(user)); } // 指定收件人,多人时用逗号分隔 InternetAddress[] tos = InternetAddress.parse(toAddr); msg.setRecipients(Message.RecipientType.TO, tos); // 标题//转码BASE64Encoder String smtpEncode = ""; if (null == smtpEncode || smtpEncode.trim().equals("")) { smtpEncode = "utf-8"; } ((MimeMessage) msg).setSubject(subject, smtpEncode); // 得到中文标题for linux,windows下不用; // 内容 msg.setText(body); // 发送时间 msg.setSentDate(new Date()); // 内容类型Content-type String smtpME = ""; if (null == smtpME || smtpME.trim().equals("")) { smtpME = "utf-8"; } msg.setContent(body, "text/html;charset=" + smtpME); // 发送 Transport.send(msg); } catch (MessagingException e) { if (DEBUG) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { if (DEBUG) { e.printStackTrace(); } } }
@POST @Produces(value = MediaType.TEXT_PLAIN) public String sendEmail( @Context HttpServletRequest request, @Context HttpServletResponse response) { String result = ""; // Recipient's email ID needs to be mentioned. String sender = request.getParameter("sender"); String receiver = request.getParameter("receiver"); String subject = request.getParameter("subject"); String messageFromSender = request.getParameter("message"); String smtp = request.getParameter("smtp"); System.out.println("display" + sender + receiver + subject + messageFromSender + smtp); if (smtp != null && sender != null && receiver != null && subject != null && messageFromSender != null) { // Recipient's email ID needs to be mentioned. String to = receiver; // Sender's email ID needs to be mentioned String from = sender; // Assuming you are sending email from localhost String host = smtp; // "smtp.wlink.com.np"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(messageFromSender + "\n\nThis message was sent on :" + getDate()); // Send message Transport.send(message); result = "Email Successfully sent"; } catch (MessagingException mex) { mex.printStackTrace(); result = "Error Occured. Please Try again"; } } return result; }
public void setMimeMessage(MimeMessage message) { this.message = message; try { extractFiles(); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } }
private void sendEmail(User u) throws UnsupportedEncodingException { String uuid = UUID.randomUUID().toString(); StringBuffer requestURL = request.getRequestURL(); int li = requestURL.lastIndexOf("/"); String url = requestURL.substring(0, li); url += "/" + "newPasswordForm?" + "uuid=" + uuid; u.setPassword(UUID.randomUUID().toString()); u.setNewPasswordKey(uuid); ls.save(u); System.out.println(url); InternetAddress ToAddress = new InternetAddress(u.getEmail(), u.getUserName(), "ISO-2022-JP"); // 送信相手 InternetAddress FromAddress = new InternetAddress("*****@*****.**", "崇城大学 和泉研究室", "ISO-2022-JP"); // 送信元(自分) Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try { message.setFrom(FromAddress); message.addRecipient(Message.RecipientType.TO, ToAddress); message.setSubject("にわるかのパスワードをリセットしました", "ISO-2022-JP"); StringBuilder sb = new StringBuilder(); sb.append(u.getUserName() + "様\n"); sb.append("\n"); sb.append("にわるかをご利用いただきありがとうございます。\n"); sb.append("\n"); sb.append("パスワードをリセット致しましたので、次のURLをクリックして新しいパスワードを設定してください。\n"); sb.append("\n"); sb.append("---------------------------------------------------------------------\n"); sb.append(url); sb.append("\n"); sb.append("---------------------------------------------------------------------\n"); sb.append("\n"); sb.append("アカウントの情報は次の通りです\n"); sb.append("にわるか ID:").append(" ").append(u.getName()); sb.append("\n"); sb.append("ユーザ名:").append(" ").append(u.getUserName()); sb.append("\n\n"); sb.append("----\n"); sb.append("\"にわるか\"は崇城大学和泉研究室で開発されています\n"); sb.append("http://sojotwitapps.appspot.com/\n"); sb.append("http://www.cis.sojo-u.ac.jp/~izumi\n"); message.setText(sb.toString(), "ISO-2022-JP"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } }