private static void sendEmail(String fromEmail, String toEmail, String subject, String body, boolean html) throws MessagingException{ MimeMessage message = new MimeMessage(MAILING_SESSION); message.setFrom(new InternetAddress(fromEmail)); InternetAddress[] addresses = InternetAddress.parse(toEmail);//one or more addresses message.addRecipients(RecipientType.TO, addresses); message.setReplyTo(addresses); message.setSubject(subject); String subType; if(html){ subType = "html"; }else{ subType = "plain"; } message.setText(body, "UTF-8", subType); Transport.send(message); }
/** * 创建一封邮件 * * @param session 和服务器交互的会话 * @param sendMail 发件人邮箱 * @param receiveMail 收件人邮箱 * @return * @throws Exception */ private MimeMessage createCodeMessage(Session session, String sendMail, String receiveMail) throws MessagingException, UnsupportedEncodingException { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sendMail, "吃在华科", "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, this.name, "UTF-8")); message.setSubject("吃在华科邮件注册验证码", "UTF-8"); String content = this.name + ",你好, 您的验证码如下<br/>" + getCode() + "<p> 您不需要回复这封邮件。<p/>"; message.setContent(content, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; }
/** * 设置发信人 * * @param name String * @param pass String */ public boolean setFrom(String from) { if (from == null || from.trim().equals("")) { from = PropertiesUtil.getString("email.send.from"); } try { String[] f = from.split(","); if (f.length > 1) { from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">"; } mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人 return true; } catch (Exception e) { logger.error(e.getLocalizedMessage()); return false; } }
/** * Returns a list of emails of admin users. * * @param addSystemAdminAddress tru if system admin should be added * @return list of emails of admin users. * @throws AddressException * @throws UnsupportedEncodingException */ public static Collection getAdminAddresslList(final boolean addSystemAdminAddress) throws AddressException { try { // Add system admin email final List result = new ArrayList(11); if (addSystemAdminAddress) { result.add(getSystemAdminAddress()); } // Add all enabled admin users emails final List adminUsers = SecurityManager.getInstance().getAdminUsers(); for (int i = 0; i < adminUsers.size(); i++) { final User user = (User) adminUsers.get(i); result.add(new InternetAddress(user.getEmail(), user.getFullName())); } return result; } catch (UnsupportedEncodingException e) { final AddressException ae = new AddressException(StringUtils.toString(e)); ae.initCause(e); throw ae; } }
/** * 设置发信人 * * @param from * @return */ public boolean setFrom(String from) { if (from == null || from.trim().equals("")) { from = PropertiesUtil.getString("email.send.from"); } try { String[] f = from.split(","); if (f.length > 1) { from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">"; } mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人 return true; } catch (Exception e) { logger.error(e.getLocalizedMessage()); return false; } }
private void send(MimeMessage msg) throws MessagingException { msg.setHeader("X-Mailer", "matrix-appservice-email"); msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, getIdentity()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.setStartTLS(cfg.getTls() > 0); transport.setRequireStartTLS(cfg.getTls() > 1); transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword()); log.info("Sending email via SMTP using {}:{}", cfg.getHost(), cfg.getPort()); try { transport.sendMessage(msg, InternetAddress.parse(getIdentity())); } catch (MessagingException e) { log.error("mmm", e); } finally { transport.close(); } }
@Override public List<String> parseAddresses(String emails) throws AddressException { String[] emailsList = new String[0]; String rawEmail = emails; if( rawEmail != null ) { rawEmail = rawEmail.replaceAll(";", " "); emailsList = rawEmail.split("\\s+"); } List<String> addresses = new ArrayList<String>(); for( String email : emailsList ) { new InternetAddress(email).validate(); addresses.add(email); } return addresses; }
public String sendMail() { mail.setPassword(Mailer.PA); mail.setHost(Mailer.HOST); mail.setSender(Mailer.SENDER); Properties properties = System.getProperties(); properties.put("mail.smtp.host", mail.getHost()); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.port", "465"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAurhentication() { return new PasswordAuthentication(mail.getSender(), mail.getPassword()); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(mail.getSender())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.getEmailId())); message.setSubject(mail.getSubject()); message.setText(mail.getMessage()); Transport.send(message, mail.getSender(),mail.getPassword()); System.out.println("Mail Sent"); return StatusCode.SUCCESS; } catch(Exception ex) { throw new RuntimeException("Error while sending mail" + ex); } }
private void sendEmail(TokenStoreEntity token, UserEntity user) { Map<String, Object> params = new HashMap<>(); String subject; String template; if (TokenStoreType.USER_ACTIVATION.equals(token.getType())){ params.put("activationUrl", baseUrl + "/registration/activate?at=" + token.getToken()); subject = "Registration Confirmation"; template = "email/registration.html"; } else { params.put("changepassUrl", baseUrl + "/changepass/update?rt=" + token.getToken()); subject = "Reset Password Confirmation"; template = "email/changepass.html"; } try { emailService.sendEmail(null, new InternetAddress(user.getEmail()), subject, params, template); } catch (AddressException e) { throw new RegistrationException("Unable to send activation link"); } }
/** * Set the sender display name on the From header * * @param name * the display name to set * @throws PackageException */ @PublicAtsApi public void setSenderName( String name ) throws PackageException { try { InternetAddress address = new InternetAddress(); String[] fromHeaders = getHeaderValues(FROM_HEADER); if (fromHeaders != null && fromHeaders.length > 0) { // parse the from header if such exists String fromHeader = fromHeaders[0]; if (fromHeader != null) { address = InternetAddress.parse(fromHeader)[0]; } } address.setPersonal(name); message.setFrom(address); } catch (ArrayIndexOutOfBoundsException aioobe) { throw new PackageException("Sender not present"); } catch (MessagingException me) { throw new PackageException(me); } catch (UnsupportedEncodingException uee) { throw new PackageException(uee); } }
/** * Set the To recipient of a mime package, the CC and BCC recipients are * cleared * * @param address the email address of the recipient * @throws PackageException */ @PublicAtsApi public void setRecipient( String address ) throws PackageException { try { // add the recipient InternetAddress inetAddress = new InternetAddress(address); message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, new InternetAddress[]{ inetAddress }); message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.CC, new InternetAddress[]{}); message.setRecipients(javax.mail.internet.MimeMessage.RecipientType.BCC, new InternetAddress[]{}); } catch (MessagingException me) { throw new PackageException(me); } }
/** * Add recipients of a specified type * * @param type the recipients' type * @param addresses the email addresses of the recipients * @throws PackageException */ @PublicAtsApi public void addRecipient( RecipientType type, String[] addresses ) throws PackageException { try { // add the recipient InternetAddress[] address = new InternetAddress[addresses.length]; for (int i = 0; i < addresses.length; i++) address[i] = new InternetAddress(addresses[i]); message.addRecipients(type.toJavamailType(), address); } catch (MessagingException me) { throw new PackageException(me); } }
/** * * @param session 和服务器交互的会话 * @param mail 邮件内容 * @return * @throws Exception */ private static MimeMessage createMimeMessage(Session session, String SendAccount, Mail mail) throws Exception { MimeMessage message = new MimeMessage(session); //From: 发件人 message.setFrom(new InternetAddress(SendAccount, mail.getPersonal(), "UTF-8")); // To: 收件人 message.setRecipients(MimeMessage.RecipientType.TO, mail.getAddresses()); // Subject: 邮件主题 message.setSubject(mail.getSubject(), "UTF-8"); // Content: 邮件正文(可以使用html标签) message.setContent(mail.getContext(), "text/html;charset=UTF-8"); // 设置发件时间 message.setSentDate(new Date()); message.saveChanges(); return message; }
private MimeMessage buildMailMessage(Session session, NotificationEvent notifyEvent, String title, String mailTemplatePath) throws MessagingException { MimeMessage message = new MimeMessage(session); // 邮件标题 message.setSubject(title); String html = IOHelper.readTxtFile(mailTemplatePath, "utf-8"); html = buildMailBody(html, notifyEvent); // 正文 message.setContent(html, "text/html;charset=utf-8"); // 发件人 message.setFrom(username); String addressStr = notifyEvent.getArg(cName); String[] toAddr = addressStr.split(","); Address[] receiver = new Address[toAddr.length]; int i = 0; for (String addr : toAddr) { if (!StringHelper.isEmpty(addr)) { receiver[i] = new InternetAddress(addr); i++; } } // 收件人 message.setRecipients(MimeMessage.RecipientType.TO, receiver); message.saveChanges(); return message; }
public static boolean setTo(String to) { if (to == null) return false; try { message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to)); } catch (Exception e) { return false; } return true; }
/** * 验证Session,进行发送信息 */ private static void createMessage(Session session){ Message message = new MimeMessage(session);// 2, 创建代表邮件的对象Message try { message.setFrom(new InternetAddress(username));// 设置发件人 message.addRecipient(RecipientType.TO, new InternetAddress(Receiver)); // 设置收件人 message.setSubject(title);// 设置标题 message.setSentDate(new Date());// 设置发送时间 // 设置正文(有链接选择text/html;charset=utf-8) message.setContent(contents, "text/html;charset=utf-8"); Transport.send(message);// 3,发送邮件Transport } catch (Exception e) { e.printStackTrace(); } }
private InternetAddress[] toInternetAddresses(List<String> recipients){ InternetAddress[] addresses = new InternetAddress[recipients.size()]; for(int i=0; i<recipients.size(); i++){ try { addresses[i] = new InternetAddress(recipients.get(i)); } catch (AddressException e) { LOGGER.error("Invalid email address",e); addresses[i] = new InternetAddress(); } } return addresses; }
/** * Converts the specified message into a {@link javax.mail.Message * javax.mail.Message}. * * @param message * the specified message * @return a {@link javax.mail.internet.MimeMessage} * @throws Exception * if converts error */ public javax.mail.Message convert2JavaMailMsg(final MailMessage message) throws Exception { if (message == null) { return null; } if (StringUtils.isBlank(message.getFrom())) { throw new MessagingException("Null from"); } if (null == message.getRecipients() || message.getRecipients().isEmpty()) { throw new MessagingException("Null recipients"); } final MimeMessage ret = new MimeMessage(getSession()); ret.setFrom(new InternetAddress(message.getFrom())); final String subject = message.getSubject(); ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B")); final String htmlBody = message.getHtmlBody(); ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8"); ret.addRecipients(javax.mail.Message.RecipientType.TO, transformRecipients(message.getRecipients())); return ret; }
public static boolean isValidEmailAddress(String email) { boolean valid = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { valid = false; } return valid; }
public boolean sendAttachMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } try { Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator)); mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress())); mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress())); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); Multipart multi = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); multi.addBodyPart(textBodyPart); for (String path : mailInfo.getAttachFileNames()) { DataSource fds = new FileDataSource(path); BodyPart fileBodyPart = new MimeBodyPart(); fileBodyPart.setDataHandler(new DataHandler(fds)); fileBodyPart.setFileName(path.substring(path.lastIndexOf("/") + 1)); multi.addBodyPart(fileBodyPart); } mailMessage.setContent(multi); mailMessage.saveChanges(); Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); return false; } }
public void send(String email, String token) throws EmailException { Properties properties = System.getProperties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", emailProperties.getSmtpHost()); properties.put("mail.smtp.port", emailProperties.getSmtpPort()); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailProperties.getUsername(), emailProperties.getPassword()); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailProperties.getUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject(messages.getMessageBy("label.pathological.reports").concat(" - ").concat(messages.getMessageBy("label.recover.password"))); message.setText(createBody(emailProperties.getApplicationCtxPath(), token)); Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); throw new EmailException(messages.getMessageBy("message.email.exception")); } }
public void report(UserSetting userSetting, SearchResult searchResult, int resultState) { if(! (boolean)config.get("enableMailReport")) return; final Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", "smtp.163.com"); props.put("mail.user", config.get("fromEmailUser")); props.put("mail.password", config.get("fromEmailPassword")); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(props.getProperty("mail.user"), props.getProperty("mail.password")); } }; Session mailSession = Session.getInstance(props, authenticator); try { MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(props.getProperty("mail.user"))); message.setRecipient(RecipientType.TO, new InternetAddress(config.get("toEmailUser").toString())); message.setSubject("PTE助手通知"); String content = String.format("账号 %s 已搜索到可用约会: 时间=%s, 地点=%s", userSetting.user.username, CalendarUtils.chinese(searchResult.apptTime), searchResult.testCenter); if(resultState > -1) { content += "<br>"; content += resultState == 1 ? "并报名成功" : "但报名失败"; } message.setContent(content, "text/html;charset=UTF-8"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); } }
/** * @desc 初始化邮件通用设置 * * @author liuliang * * @return MimeMessage * @throws MessagingException */ private MimeMessage initialMessage() throws MessagingException{ // 配置发送邮件的环境属性 final Properties props = new Properties(); // 表示SMTP发送邮件,需要进行身份验证 props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", MAIL_SMTP_HOST); props.put("mail.smtp.port", MAIL_SMTP_PORT); // 发件人的账号 props.put("mail.user", emailSenderName); // 访问SMTP服务时需要提供的密码 props.put("mail.password", emailSenderPassword); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //用户名、密码 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 使用环境属性和授权信息,创建邮件会话 Session mailSession = Session.getInstance(props, authenticator); // 创建邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 InternetAddress form = new InternetAddress(props.getProperty("mail.user")); message.setFrom(form); return message; }
/** * 发邮件处理 * * @param toAddr * 邮件地址 * @param content * 邮件内容 * @return 成功标识 */ public static boolean sendMail(String toAddr, String title, String content, boolean isHtmlFormat) { final String username = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_USERNAME); final String password = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_PASSWORD); Properties props = new Properties(); props.put("mail.smtp.auth", YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_AUTH, true)); props.put("mail.smtp.starttls.enable", YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_STARTTLS_ENABLE, true)); props.put("mail.smtp.host", YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_HOST)); props.put("mail.smtp.port", YiDuConstants.yiduConf.getInt(YiDuConfig.MAIL_SMTP_PORT, 25)); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_FROM))); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddr)); message.setSubject(title); if (isHtmlFormat) { message.setContent(content, "text/html"); } else { message.setText(content); } Transport.send(message); } catch (MessagingException e) { logger.warn(e); return false; } return true; }
public static String validateEmailStandard(String email){ try{ InternetAddress testEmail = new InternetAddress(email); testEmail.validate(); return email + " is a valid email address"; }catch(AddressException e){ return email + " is not a valid email address"; } }
/** * Is valid email address boolean. * * @param email the email * @return the boolean */ public static boolean isValidEmailAddress(final String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; }
private InternetAddress[] getUserInternetAdresses(final SimpleUserOrg user, final String fullName) throws UnsupportedEncodingException { final InternetAddress[] internetAddresses = new InternetAddress[user.getMails().size()]; for (int i = 0; i < user.getMails().size(); i++) { internetAddresses[i] = new InternetAddress(user.getMails().get(i), fullName, StandardCharsets.UTF_8.name()); } return internetAddresses; }
public void sendMultipartMessage(String subject, String[] to, String text, String attach) throws MessagingException, IOException { MimeMessage message = new MimeMessage(senderSession); message.setFrom(new InternetAddress(pManager.get_SENDER_From())); // FROM for(int i=0; i < to.length; i++) { if(!to[i].equals("")) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); // TO } } message.setSubject(subject); //SUBJECT Multipart mp = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setText(text); mp.addBodyPart(textPart); // TEXT MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(attach); mp.addBodyPart(attachPart); // ATTACH message.setContent(mp); transport.sendMessage(message, message.getAllRecipients()); }
private Message buildEmailMessage(EmailInfo emailInfo) throws AddressException, MessagingException, UnsupportedEncodingException { MimeMessage message = new MimeMessage(this.session); message.setFrom(new InternetAddress(emailInfo.getFrom(), "网页更新订阅系统", "UTF-8")); message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailInfo.getTo())); Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(emailInfo.getContent(), "text/html;charset=UTF-8"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.setSubject(emailInfo.getTitle()); message.saveChanges(); return message; }
private static MimeMessage createMimeMessage(MessageBean msgBean, String mimeSubtype, Session session) throws MessagingException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(msgBean.getFrom())); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(msgBean.getTo())); msg.setSubject(msgBean.getSubject()); msg.setText(msgBean.getContent(), Charset.defaultCharset().name(), mimeSubtype); return msg; }
public static boolean isValidEmailAddress(String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; }