Java Code Examples for javax.mail.Message#setRecipients()
The following examples show how to use
javax.mail.Message#setRecipients() .
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: MailUtils.java From translationstudio8 with GNU General Public License v2.0 | 6 votes |
/** * 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样. * @param message * 邮件对象 * @throws MessagingException * the messaging exception */ public static void removeDumplicate(Message message) throws MessagingException { Address[] from = message.getFrom(); Address[] to = message.getRecipients(Message.RecipientType.TO); Address[] cc = message.getRecipients(Message.RecipientType.CC); Address[] bcc = message.getRecipients(Message.RecipientType.BCC); Address[] tonew = removeDuplicate(from, to); Address[] ccnew = removeDuplicate(from, cc); Address[] bccnew = removeDuplicate(from, bcc); if (tonew != null) { message.setRecipients(Message.RecipientType.TO, tonew); } if (ccnew != null) { message.setRecipients(Message.RecipientType.CC, ccnew); } if (bccnew != null) { message.setRecipients(Message.RecipientType.BCC, bccnew); } }
Example 2
Source File: SMTPAppender.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * Address message. * @param msg message, may not be null. * @throws MessagingException thrown if error addressing message. */ protected void addressMessage(final Message msg) throws MessagingException { if (from != null) { msg.setFrom(getAddress(from)); } else { msg.setFrom(); } if (to != null && to.length() > 0) { msg.setRecipients(Message.RecipientType.TO, parseAddress(to)); } //Add CC receipients if defined. if (cc != null && cc.length() > 0) { msg.setRecipients(Message.RecipientType.CC, parseAddress(cc)); } //Add BCC receipients if defined. if (bcc != null && bcc.length() > 0) { msg.setRecipients(Message.RecipientType.BCC, parseAddress(bcc)); } }
Example 3
Source File: MailSenderUtil.java From kardio with Apache License 2.0 | 5 votes |
/** * Send Mail Alert. * * @param Message */ public static void sendMail(String messageText, String toMail, String subject){ Properties props = new Properties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_IP)); props.put("mail.smtp.port", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PORT)); Session session = null; String mailAuthUserName = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_USERNAME); String mailAuthPassword = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PASSWORD); if (mailAuthUserName != null && mailAuthUserName.length() > 0 && mailAuthPassword != null && mailAuthPassword.length() > 0) { props.put("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailAuthUserName, mailAuthPassword); } }; session = Session.getDefaultInstance(props, auth); } else { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); } try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(propertyUtil.getValue(SurveillerConstants.MAIL_FROM_ADDRESS) )); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail)); message.setSubject(subject); message.setText(messageText); Transport.send(message); } catch (MessagingException me) { logger.error("Error in Mail Sending: " + me); throw new RuntimeException(me.getMessage()); } logger.debug("Mail Sent to: " + toMail); }
Example 4
Source File: EmailNotificationService.java From nifi with Apache License 2.0 | 5 votes |
@Override public void notify(final NotificationContext context, final NotificationType notificationType, final String subject, final String messageText) throws NotificationFailedException { final Properties properties = getMailProperties(context); final Session mailSession = createMailSession(properties); final Message message = new MimeMessage(mailSession); try { message.setFrom(InternetAddress.parse(context.getProperty(FROM).evaluateAttributeExpressions().getValue())[0]); final InternetAddress[] toAddresses = toInetAddresses(context.getProperty(TO).evaluateAttributeExpressions().getValue()); message.setRecipients(RecipientType.TO, toAddresses); final InternetAddress[] ccAddresses = toInetAddresses(context.getProperty(CC).evaluateAttributeExpressions().getValue()); message.setRecipients(RecipientType.CC, ccAddresses); final InternetAddress[] bccAddresses = toInetAddresses(context.getProperty(BCC).evaluateAttributeExpressions().getValue()); message.setRecipients(RecipientType.BCC, bccAddresses); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions().getValue()); message.setSubject(subject); final String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions().getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); Transport.send(message); } catch (final ProcessException | MessagingException e) { throw new NotificationFailedException("Failed to send E-mail Notification", e); } }
Example 5
Source File: TestMailClient.java From holdmail with Apache License 2.0 | 5 votes |
public void sendResourceEmail(String resourceName, String sender, String recipient, String subjectOverride) { try { InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName); if (resource == null) { throw new MessagingException("Couldn't find resource at: " + resourceName); } Message message = new MimeMessage(session, resource); // wipe out ALL exisitng recipients message.setRecipients(Message.RecipientType.TO, new Address[] {}); message.setRecipients(Message.RecipientType.CC, new Address[] {}); message.setRecipients(Message.RecipientType.BCC, new Address[] {}); // then set the new data message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setFrom(InternetAddress.parse(sender)[0]); if(StringUtils.isNotBlank(subjectOverride)) { message.setSubject(subjectOverride); } Transport.send(message); logger.info("Outgoing mail forwarded to " + recipient); } catch (MessagingException e) { throw new HoldMailException("couldn't send mail: " + e.getMessage(), e); } }
Example 6
Source File: MailSender.java From SensorWebClient with GNU General Public License v2.0 | 5 votes |
public static void sendRegisterMail(String address, String id, String userName) { LOGGER.debug("send register mail to: " + address); String link = "?user=" + id; String tempText_de = SesConfig.mailTextRegister_de.replace("_NAME_", userName); String tempText_en = SesConfig.mailTextRegister_en.replace("_NAME_", userName); String text = tempText_en + "\n" + tempText_de + "\n" + SesConfig.URL + link; Session session = Session.getDefaultInstance(getProperties(), getMailAuthenticator()); try { // create a new message Message msg = new MimeMessage(session); // set sender and receiver msg.setFrom(new InternetAddress(SesConfig.SENDER_ADDRESS)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false)); // set subject to mail msg.setSubject(SesConfig.mailSubjectRegister_en + "/" + SesConfig.mailSubjectRegister_de); msg.setText(text); msg.setSentDate(new Date()); // send message Transport.send(msg); LOGGER.debug("mail send succesfully done"); } catch (Exception e) { LOGGER.error("Error occured while sending register mail: " + e.getMessage(), e); } }
Example 7
Source File: Enviar_email.java From redesocial with MIT License | 5 votes |
public static void main(String[] args) { Properties props = new Properties(); /** Parâmetros de conexão com servidor Gmail */ 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("[email protected]", "tjm123456"); } }); /** Ativa Debug para sessão */ session.setDebug(true); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); //Remetente Address[] toUser = InternetAddress //Destinatário(s) .parse("[email protected]"); message.setRecipients(Message.RecipientType.TO, toUser); message.setSubject("Enviando email com JavaMail");//Assunto message.setText("Enviei este email utilizando JavaMail com minha conta GMail!"); /**Método para enviar a mensagem criada*/ Transport.send(message); System.out.println("Feito!!!"); } catch (MessagingException e) { throw new RuntimeException(e); } }
Example 8
Source File: MailSender.java From SensorWebClient with GNU General Public License v2.0 | 5 votes |
public static boolean sendSensorDeactivatedMail(String address, String sensorID) { LOGGER.debug("send email validation mail to: " + address); String text = SesConfig.mailSubjectSensor_en + ": " + "\n" + SesConfig.mailSubjectSensor_de + ": " + "\n\n" + sensorID; Session session = Session.getDefaultInstance(getProperties(), getMailAuthenticator()); try { // create a message Message msg = new MimeMessage(session); // set sender and receiver msg.setFrom(new InternetAddress(SesConfig.SENDER_ADDRESS)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false)); // set subject msg.setSubject(SesConfig.mailSubjectSensor_en + "/" + SesConfig.mailSubjectSensor_de); msg.setText(text); msg.setSentDate(new Date()); // send mail Transport.send(msg); LOGGER.debug("mail send succesfully done"); return true; } catch (MessagingException e) { LOGGER.error("Error occured while sending sensor deactivation mail: " + e.getMessage(), e); } return false; }
Example 9
Source File: TestListenSMTP.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testListenSMTP() throws Exception { final ListenSMTP processor = new ListenSMTP(); final TestRunner runner = TestRunners.newTestRunner(processor); final int port = NetworkUtils.availablePort(); runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port)); runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3"); runner.run(1, false); assertTrue(String.format("expected server listening on %s:%d", "localhost", port), NetworkUtils.isListening("localhost", port, 5000)); final Properties config = new Properties(); config.put("mail.smtp.host", "localhost"); config.put("mail.smtp.port", String.valueOf(port)); config.put("mail.smtp.connectiontimeout", "5000"); config.put("mail.smtp.timeout", "5000"); config.put("mail.smtp.writetimeout", "5000"); final Session session = Session.getInstance(config); session.setDebug(true); final int numMessages = 5; for (int i = 0; i < numMessages; i++) { final Message email = new MimeMessage(session); email.setFrom(new InternetAddress("[email protected]")); email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); email.setSubject("This is a test"); email.setText("MSG-" + i); Transport.send(email); } runner.shutdown(); runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, numMessages); }
Example 10
Source File: MailService.java From commafeed with Apache License 2.0 | 5 votes |
public void sendMail(User user, String subject, String content) throws Exception { ApplicationSettings settings = config.getApplicationSettings(); final String username = settings.getSmtpUserName(); final String password = settings.getSmtpPassword(); final String fromAddress = Optional.ofNullable(settings.getSmtpFromAddress()).orElse(settings.getSmtpUserName()); String dest = user.getEmail(); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "" + settings.isSmtpTls()); props.put("mail.smtp.host", settings.getSmtpHost()); props.put("mail.smtp.port", "" + settings.getSmtpPort()); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress, "CommaFeed")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dest)); message.setSubject("CommaFeed - " + subject); message.setContent(content, "text/html; charset=utf-8"); Transport.send(message); }
Example 11
Source File: CustomerMasterService.java From jVoiD with Apache License 2.0 | 5 votes |
public void sendEmail(String email, String password){ Properties properties = System.getProperties(); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", false); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", 587); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "test123"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Reset Password"); String content = "Your new password is " + password; message.setText(content); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
Example 12
Source File: ExceptionNotificationServiceImpl.java From telekom-workflow-engine with MIT License | 5 votes |
private void sendEmail( String from, String to, String subject, String body ){ log.info( "Sending exception email from:{} to:{} subject:{}", from, to, subject ); try{ Properties props = new Properties(); props.put( "mail.smtp.host", smtpHost ); if (StringUtils.isNotBlank(smtpPort)) { props.put( "mail.smtp.port", smtpPort ); } Authenticator authenticator = null; if (StringUtils.isNotBlank(smtpUsername)) { props.put( "mail.smtp.auth", true ); authenticator = new SmtpAuthenticator(); } Session session = Session.getDefaultInstance( props, authenticator ); Message msg = new MimeMessage( session ); msg.setFrom( new InternetAddress( from ) ); InternetAddress[] addresses = InternetAddress.parse( to ); msg.setRecipients( Message.RecipientType.TO, addresses ); msg.setSubject( subject ); msg.setSentDate( new Date() ); msg.setText( body ); Transport.send( msg ); } catch( Exception e ){ log.warn( "Sending email failed: ", e ); } }
Example 13
Source File: Monitor.java From IBMonitorService with GNU General Public License v3.0 | 5 votes |
private void sendNotification(String sendTo, String sendCC, String subject, String message) { try { // create a message Message msg = new MimeMessage(emailSession); // set the from and to address InternetAddress addressFrom = new InternetAddress(IBMonitorSvc.emailReplyTo); msg.setFrom(addressFrom); if (!sendTo.equals("")){ InternetAddress[] addressTo = parseRecipients(sendTo); msg.setRecipients(Message.RecipientType.TO, addressTo); } if (!sendCC.equals("")){ InternetAddress[] addressCC = parseRecipients(sendCC); msg.setRecipients(Message.RecipientType.CC, addressCC); } // Setting the Subject and Content Type msg.setSubject(subject); message = message + CRLF + CRLF + "This is an automated email. Please do not reply to sender."; msg.setContent(message, "text/plain"); Transport.send(msg); } catch(MessagingException me) { logger.info("Error sending secure email message using password auth - " + me.getMessage()); } catch (Exception e) { logger.info("Exception caught when attempting to send email: " + e.getMessage()); } }
Example 14
Source File: ScriptValuesAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 4 votes |
public static void sendMail( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if ( ArgList.length == 5 ) { try { // Set the host smtp address Properties props = new Properties(); props.put( "mail.smtp.host", ArgList[0] ); // create some properties and get the default Session Session session = Session.getDefaultInstance( props, null ); session.setDebug( debug ); // create a message Message msg = new MimeMessage( session ); // set the from and to address InternetAddress addressFrom = new InternetAddress( (String) ArgList[1] ); msg.setFrom( addressFrom ); // Get Recipients String[] strArrRecipients = ( (String) ArgList[2] ).split( "," ); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for ( int i = 0; i < strArrRecipients.length; i++ ) { addressTo[i] = new InternetAddress( strArrRecipients[i] ); } msg.setRecipients( Message.RecipientType.TO, addressTo ); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader( "MyHeaderName", "myHeaderValue" ); // Setting the Subject and Content Type msg.setSubject( (String) ArgList[3] ); msg.setContent( ArgList[4], "text/plain" ); Transport.send( msg ); } catch ( Exception e ) { throw Context.reportRuntimeError( "sendMail: " + e.toString() ); } } else { throw Context.reportRuntimeError( "The function call sendMail requires 5 arguments." ); } }
Example 15
Source File: ScriptAddedFunctions.java From pentaho-kettle with Apache License 2.0 | 4 votes |
public static void sendMail( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext ) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if ( ArgList.length == 5 ) { try { // Set the host smtp address Properties props = new Properties(); props.put( "mail.smtp.host", ArgList[0] ); // create some properties and get the default Session Session session = Session.getDefaultInstance( props, null ); session.setDebug( debug ); // create a message Message msg = new MimeMessage( session ); // set the from and to address InternetAddress addressFrom = new InternetAddress( (String) ArgList[1] ); msg.setFrom( addressFrom ); // Get Recipients String[] strArrRecipients = ( (String) ArgList[2] ).split( "," ); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for ( int i = 0; i < strArrRecipients.length; i++ ) { addressTo[i] = new InternetAddress( strArrRecipients[i] ); } msg.setRecipients( Message.RecipientType.TO, addressTo ); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader( "MyHeaderName", "myHeaderValue" ); // Setting the Subject and Content Type msg.setSubject( (String) ArgList[3] ); msg.setContent( ArgList[4], "text/plain" ); Transport.send( msg ); } catch ( Exception e ) { throw new RuntimeException( "sendMail: " + e.toString() ); } } else { throw new RuntimeException( "The function call sendMail requires 5 arguments." ); } }
Example 16
Source File: MailClient.java From ankush with GNU Lesser General Public License v3.0 | 4 votes |
/** * This method actually send the mail. * * @param mailMsg the actual mail message content in form of MailMsg object that * includes recipients list, subject & the message * @return returns success status of sending mail * @throws Exception the exception */ public boolean sendMail(MailMsg mailMsg) throws Exception { boolean mailSent = false; Message msg = new MimeMessage(session); String from = mailMsg.getFrom(); if (from == null) { from = mailConf.getEmailAddress(); } if ((from != null) && (!from.equals(""))) { InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); } // convert delimited list to array for to, cc & bcc msg.setRecipients(Message.RecipientType.TO, getInternetAddress(getRecipients(mailMsg.getTo()))); msg.setRecipients(Message.RecipientType.CC, getInternetAddress(getRecipients(mailMsg.getCc()))); msg.setRecipients(Message.RecipientType.BCC, getInternetAddress(getRecipients(mailMsg.getBcc()))); msg.setSubject(mailMsg.getSubject()); String contentType = mailMsg.getContentType(); if (contentType == null) { contentType = "text/plain"; } msg.setContent(mailMsg.getMessage(), contentType); try { Transport.send(msg); mailSent = true; } catch (Exception e) { logger.error("Error in Sending mail @ Mail client : " + e.getMessage()); e.printStackTrace(); } return mailSent; }
Example 17
Source File: FP.java From Web-Based-Graphical-Password-Authentication-System with MIT License | 4 votes |
public static void send(String tomail,String msg){ // Recipient's email ID needs to be mentioned. //String to = "[email protected]"; String to = tomail; // Sender's email ID needs to be mentioned String from = "[email protected]";//change accordingly final String username = "[email protected]";//change accordingly final String password = "rohanaudia8";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Login Credentials"); // Now set the actual message message.setText("" + msg); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }
Example 18
Source File: ScriptValuesAddedFunctions.java From hop with Apache License 2.0 | 4 votes |
public static void sendMail( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if ( ArgList.length == 5 ) { try { // Set the host smtp address Properties props = new Properties(); props.put( "mail.smtp.host", ArgList[ 0 ] ); // create some properties and get the default Session Session session = Session.getDefaultInstance( props, null ); session.setDebug( debug ); // create a message Message msg = new MimeMessage( session ); // set the from and to address InternetAddress addressFrom = new InternetAddress( (String) ArgList[ 1 ] ); msg.setFrom( addressFrom ); // Get Recipients String[] strArrRecipients = ( (String) ArgList[ 2 ] ).split( "," ); InternetAddress[] addressTo = new InternetAddress[ strArrRecipients.length ]; for ( int i = 0; i < strArrRecipients.length; i++ ) { addressTo[ i ] = new InternetAddress( strArrRecipients[ i ] ); } msg.setRecipients( Message.RecipientType.TO, addressTo ); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader( "MyHeaderName", "myHeaderValue" ); // Setting the Subject and Content Type msg.setSubject( (String) ArgList[ 3 ] ); msg.setContent( ArgList[ 4 ], "text/plain" ); Transport.send( msg ); } catch ( Exception e ) { throw Context.reportRuntimeError( "sendMail: " + e.toString() ); } } else { throw Context.reportRuntimeError( "The function call sendMail requires 5 arguments." ); } }
Example 19
Source File: ScriptAddedFunctions.java From hop with Apache License 2.0 | 4 votes |
public static void sendMail( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext ) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if ( ArgList.length == 5 ) { try { // Set the host smtp address Properties props = new Properties(); props.put( "mail.smtp.host", ArgList[ 0 ] ); // create some properties and get the default Session Session session = Session.getDefaultInstance( props, null ); session.setDebug( debug ); // create a message Message msg = new MimeMessage( session ); // set the from and to address InternetAddress addressFrom = new InternetAddress( (String) ArgList[ 1 ] ); msg.setFrom( addressFrom ); // Get Recipients String[] strArrRecipients = ( (String) ArgList[ 2 ] ).split( "," ); InternetAddress[] addressTo = new InternetAddress[ strArrRecipients.length ]; for ( int i = 0; i < strArrRecipients.length; i++ ) { addressTo[ i ] = new InternetAddress( strArrRecipients[ i ] ); } msg.setRecipients( Message.RecipientType.TO, addressTo ); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader( "MyHeaderName", "myHeaderValue" ); // Setting the Subject and Content Type msg.setSubject( (String) ArgList[ 3 ] ); msg.setContent( ArgList[ 4 ], "text/plain" ); Transport.send( msg ); } catch ( Exception e ) { throw new RuntimeException( "sendMail: " + e.toString() ); } } else { throw new RuntimeException( "The function call sendMail requires 5 arguments." ); } }
Example 20
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{ } }