Java Code Examples for javax.mail.Message#saveChanges()
The following examples show how to use
javax.mail.Message#saveChanges() .
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: Pop3Util.java From anyline with Apache License 2.0 | 7 votes |
/** * * @param fr 发送人姓名 * @param to 收件人地址 * @param title 邮件主题 * @param content 邮件内容 * @return return */ public boolean send(String fr, String to, String title, String content) { log.warn("[send email][fr:{}][to:{}][title:{}][centent:{}]", fr, to, title, content); try { Session mailSession = Session.getDefaultInstance(props); Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(config.ACCOUNT, fr)); msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); msg.setSubject(title); msg.setContent(content, "text/html;charset=UTF-8"); msg.saveChanges(); Transport transport = mailSession.getTransport("smtp"); transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example 2
Source File: MailUtil.java From anyline with Apache License 2.0 | 7 votes |
/** * * @param fr 发送人姓名 fr 发送人姓名 * @param to 收件人地址 to 收件人地址 * @param title 邮件主题 title 邮件主题 * @param content 邮件内容 content 邮件内容 * @return return */ public boolean send(String fr, String to, String title, String content) { log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", fr,to,title,content); try { Session mailSession = Session.getDefaultInstance(props); Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(config.ACCOUNT,fr)); msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); msg.setSubject(title + ""); msg.setContent(content + "", "text/html;charset=UTF-8"); msg.saveChanges(); Transport transport = mailSession.getTransport("smtp"); transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example 3
Source File: EmailUtils.java From tools with MIT License | 6 votes |
/** * 发送普通email,支持html格式 * * @param subject 主题 * @param body 文本内容 * @param tos 接收方邮件地址,多个逗号隔开 * @param copyTo 抄送人,可以多个,逗号隔开,不需要抄送,传null或者"" * @return true为发送成功 */ public boolean sendEmail(String subject, String body, String tos, String copyTo) { if (ParamUtils.isEmpty(tos)) { throw new NullPointerException("The parameter tos cannot be null"); } try { Properties props = getProperties(); Session session = Session.getInstance(props); Message msg = setSubjectWithFrom(subject, session); setRecipient(tos, copyTo, msg); MimeMultipart mm = getMimeMultipart(body); msg.setContent(mm); msg.saveChanges(); startSend(session, msg); } catch (MessagingException e) { e.printStackTrace(); } return true; }
Example 4
Source File: FlowedMessageUtils.java From james-project with Apache License 2.0 | 6 votes |
/** * If the message is <code>format=flowed</code> * set the encoded version as message content. */ public static void deflowMessage(Message m) throws MessagingException, IOException { ContentType ct = new ContentType(m.getContentType()); String format = ct.getParameter("format"); if (ct.getBaseType().equals("text/plain") && format != null && format.equalsIgnoreCase("flowed")) { String delSp = ct.getParameter("delsp"); String deflowed = deflow((String) m.getContent(), delSp != null && delSp.equalsIgnoreCase("yes")); ct.getParameterList().remove("format"); ct.getParameterList().remove("delsp"); if (ct.toString().contains("flowed")) { LOGGER.error("FlowedMessageUtils dind't remove the flowed correctly"); } m.setContent(deflowed, ct.toString()); m.saveChanges(); } }
Example 5
Source File: FlowedMessageUtils.java From james-project with Apache License 2.0 | 6 votes |
/** * Encodes the message content (if text/plain). */ public static void flowMessage(Message m, boolean delSp, int width) throws MessagingException, IOException { ContentType ct = new ContentType(m.getContentType()); if (!ct.getBaseType().equals("text/plain")) { return; } String format = ct.getParameter("format"); String text = format != null && format.equals("flowed") ? deflow(m) : (String) m.getContent(); String coded = flow(text, delSp, width); ct.setParameter("format", "flowed"); if (delSp) { ct.setParameter("delsp", "yes"); } m.setContent(coded, ct.toString()); m.saveChanges(); }
Example 6
Source File: EmailUtils.java From tools with MIT License | 5 votes |
/** * 发送带附件的email,文本支持html格式 * * @param subject 主题 * @param body 文本内容 * @param files 附件地址 * @param tos 接收方邮件地址,多个逗号隔开 * @param copyTo 抄送人,可以多个,逗号隔开,不需要抄送,传null或者"" * @return true为发送成功 */ public boolean sendEmail(String subject, String body, String[] files, String tos, String copyTo) { if (ParamUtils.isEmpty(tos)) { throw new NullPointerException("The parameter tos cannot be null"); } try { Properties props = getProperties(); Session session = Session.getInstance(props); Message msg = setSubjectWithFrom(subject, session); setRecipient(tos, copyTo, msg); // 设置邮件主体内容(包括html文本和附件) MimeMultipart mm = getMimeMultipart(body); // 设置多个附件 if (ParamUtils.isNotEmpty(files)) { for (String f : files) { // 设置附件部分 MimeBodyPart attachment = new MimeBodyPart(); // 读取文件 DataHandler dh = new DataHandler(new FileDataSource(f)); // 将文件关联到附件上 attachment.setDataHandler(dh); // 设置附件的文件名(需要编码避免中文乱码) attachment.setFileName(MimeUtility.encodeText(dh.getName())); mm.addBodyPart(attachment); } } msg.setContent(mm); msg.saveChanges(); startSend(session, msg); } catch (Exception e) { throw new IllegalStateException(e.getMessage()); } return true; }
Example 7
Source File: DefaultMailService.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
private void sendMessage ( final Message message ) throws MessagingException, NoSuchProviderException { final ClassLoader oldClassLoader = Thread.currentThread ().getContextClassLoader (); Thread.currentThread ().setContextClassLoader ( getClass ().getClassLoader () ); try { // commit message.saveChanges (); // connect final Transport transport = this.session.getTransport (); transport.connect (); // send try { transport.sendMessage ( message, message.getAllRecipients () ); } finally { // close transport.close (); } } finally { Thread.currentThread ().setContextClassLoader ( oldClassLoader ); } }
Example 8
Source File: OnlyText.java From james-project with Apache License 2.0 | 5 votes |
private static void setContentFromPart(Message m, Part p, String newText, boolean setTextPlain) throws MessagingException, IOException { String contentType = p.getContentType(); if (setTextPlain) { ContentType ct = new ContentType(contentType); ct.setPrimaryType("text"); ct.setSubType("plain"); contentType = ct.toString(); } m.setContent(newText != null ? newText : p.getContent(), contentType); String[] h = p.getHeader("Content-Transfer-Encoding"); if (h != null && h.length > 0) { m.setHeader("Content-Transfer-Encoding", h[0]); } m.saveChanges(); }
Example 9
Source File: MailSender.java From neoscada with Eclipse Public License 1.0 | 4 votes |
public void send ( final String subject, final String text ) throws MessagingException { final Message message = new MimeMessage ( this.session ); if ( this.from != null ) { message.setFrom ( this.from ); } else { message.setFrom (); } message.setHeader ( "Return-Path", "<>" ); message.setRecipients ( javax.mail.Message.RecipientType.TO, this.to ); message.setSubject ( subject ); message.setText ( text ); message.saveChanges (); final Transport transport = this.session.getTransport (); logger.debug ( "Connecting transport..." ); transport.connect (); logger.debug ( "Connecting transport... done!" ); try { logger.debug ( "Sending message..." ); transport.sendMessage ( message, message.getAllRecipients () ); logger.debug ( "Sending message... done!" ); } finally { logger.debug ( "Closing transport..." ); try { transport.close (); logger.debug ( "Closing transport... done!" ); } catch ( final Exception e ) { logger.info ( "Failed to close transport", e ); } } }
Example 10
Source File: SimpleSmtpServerTest.java From dumbster with Apache License 2.0 | 4 votes |
@Test public void testSendTwoMsgsWithLogin() throws Exception { String serverHost = "localhost"; String from = "[email protected]"; String to = "[email protected]"; String subject = "Test"; String body = "Test Body"; Properties props = System.getProperties(); if (serverHost != null) { props.setProperty("mail.smtp.host", serverHost); } Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { msg.setFrom(); } InternetAddress.parse(to, false); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject); msg.setText(body); msg.setHeader("X-Mailer", "musala"); msg.setSentDate(new Date()); msg.saveChanges(); Transport transport = null; try { transport = session.getTransport("smtp"); transport.connect(serverHost, server.getPort(), "ddd", "ddd"); transport.sendMessage(msg, InternetAddress.parse(to, false)); transport.sendMessage(msg, InternetAddress.parse("[email protected]", false)); } finally { if (transport != null) { transport.close(); } } List<SmtpMessage> emails = this.server.getReceivedEmails(); assertThat(emails, hasSize(2)); SmtpMessage email = emails.get(0); assertTrue(email.getHeaderValue("Subject").equals("Test")); assertTrue(email.getBody().equals("Test Body")); }
Example 11
Source File: MailManager.java From Cynthia with GNU General Public License v2.0 | 4 votes |
/** * @description:send mail * @date:2014-5-6 下午12:11:34 * @version:v1.0 * @param subject:mail subject * @param recievers:mail recievers * @param content:mail content * @return:if mail send success */ public static boolean sendMail(String fromUser, String subject,String[] recievers,String content){ try{ Properties props = ConfigManager.getEmailProperties(); //配置中定义不发送邮件 if (props.getProperty("mail.enable") == null || !props.getProperty("mail.enable").equals("true")) { System.out.println("there is a mail not send by config!"); return true; } //创建一个程序与邮件服务器的通信 Session mailConnection = Session.getInstance(props,null); Message msg = new MimeMessage(mailConnection); //设置发送人和接受人 Address sender = new InternetAddress(props.getProperty("mail.user")); //单个接收人 //Address receiver = new InternetAddress("[email protected]"); //多个接收人 StringBuffer buffer = new StringBuffer(); for (String reciever : recievers) { buffer.append(buffer.length() > 0 ? ",":"").append(reciever); } String all = buffer.toString(); System.out.println("send Mail,mailList:" + all); msg.setFrom(sender); Set<InternetAddress> toUserSet = new HashSet<InternetAddress>(); //邮箱有效性较验 for (int i = 0; i < recievers.length; i++) { if(recievers[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")){ toUserSet.add(new InternetAddress(recievers[i].trim())); } } msg.setRecipients(Message.RecipientType.TO, toUserSet.toArray(new InternetAddress[0])); //设置邮件主题 msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B")); //中文乱码问题 //设置邮件内容 BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent( content, "text/html; charset=utf-8" ); // 中文 Multipart multipart = new MimeMultipart(); multipart.addBodyPart( messageBodyPart ); msg.setContent(multipart); /**********************发送附件************************/ // //新建一个MimeMultipart对象用来存放多个BodyPart对象 // Multipart mtp=new MimeMultipart(); // //------设置信件文本内容------ // //新建一个存放信件内容的BodyPart对象 // BodyPart mdp=new MimeBodyPart(); // //给BodyPart对象设置内容和格式/编码方式 // mdp.setContent("hello","text/html;charset=gb2312"); // //将含有信件内容的BodyPart加入到MimeMultipart对象中 // mtp.addBodyPart(mdp); // // //设置信件的附件(用本地机上的文件作为附件) // mdp=new MimeBodyPart(); // FileDataSource fds=new FileDataSource("f:/webservice.doc"); // DataHandler dh=new DataHandler(fds); // mdp.setFileName("webservice.doc");//可以和原文件名不一致 // mdp.setDataHandler(dh); // mtp.addBodyPart(mdp); // //把mtp作为消息对象的内容 // msg.setContent(mtp); /**********************发送附件结束************************/ //先进行存储邮件 msg.saveChanges(); Transport trans = mailConnection.getTransport(props.getProperty("mail.protocal")); //邮件服务器名,用户名,密码 trans.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"), props.getProperty("mail.pass")); trans.sendMessage(msg, msg.getAllRecipients()); //关闭通道 if (trans.isConnected()) { trans.close(); } return true; }catch(Exception e) { System.err.println(e); return false; } finally{ } }