Java Code Examples for javax.mail.internet.InternetAddress

The following are top voted examples for showing how to use javax.mail.internet.InternetAddress. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mastering-Java-EE-Development-with-WildFly   File: SendMail.java   View source code 7 votes vote down vote up
public void completeClientSend(String mailServer, String... credentials) throws AddressException, MessagingException {
	if (credentials != null && credentials.length > 1) {
		// Step1
		logger.info("\n 1st ===> setup Mail Server Properties..");
		logger.info("Mail Server Properties have been setup successfully..");
		// Step2
		logger.info("\n\n 2nd ===> get Mail .");
		getMailSession = getDefaultInstance(mailServerProperties, null);
		generateMailMessage = new MimeMessage(getMailSession);
		generateMailMessage.addRecipient(TO, new InternetAddress("[email protected].it"));
		generateMailMessage.addRecipient(CC, new InternetAddress("[email protected]"));
		generateMailMessage.setSubject("Greetings from Vige..");
		String emailBody = "Test email by Vige.it JavaMail API example. " + "<br><br> Regards, <br>Vige Admin";
		generateMailMessage.setContent(emailBody, "text/html");
		logger.info("Mail Session has been created successfully..");
		// Step3
		logger.info("\n\n 3rd ===> Get Session and Send mail");
		Transport transport = getMailSession.getTransport("smtp");
		// Enter your correct gmail UserID and Password
		// if you have 2FA enabled then provide App Specific Password
		transport.connect(mailServer, credentials[0], credentials[1]);
		transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
		transport.close();
	}
}
 
Example 2
Project: datarouter   File: DatarouterEmailTool.java   View source code 7 votes vote down vote up
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);
}
 
Example 3
Project: HustEating   File: Mail.java   View source code 6 votes vote down vote up
/**
 * 创建一封邮件
 *
 * @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;
}
 
Example 4
Project: parabuild-ci   File: SSTestRecepientListComposer.java   View source code 6 votes vote down vote up
/**
 * Tests add security groups as build watchers
 */
public void test_cr948_addSecurityGroupWatcher() throws AddressException {
  // make test watcher list
  final String TEST_VALID_WATCHER_GROUP_NAME = "Test group 1";
  final List watchers = new ArrayList(1);
  watchers.add(new BuildWatcher(TEST_VALID_WATCHER_GROUP_NAME, BuildWatcher.LEVEL_SYSTEM_ERROR));
  composer.addWatchers(BuildWatcher.LEVEL_BROKEN, watchers);

  // make recipients
  boolean emailFromGroupUserFound = false;
  final EmailRecipients recipients = composer.makeRecipients(cm.getBuildRun(3), new HashMap(), false, true, false, true, BuildWatcher.LEVEL_BROKEN);
  for (final Iterator i = recipients.getAllAddresses().iterator(); i.hasNext();) {
    final String address = ((InternetAddress) i.next()).getAddress();
    emailFromGroupUserFound = emailFromGroupUserFound || address.equals("[email protected]");
  }
  assertTrue(emailFromGroupUserFound);
}
 
Example 5
Project: iBase4J   File: EmailSender.java   View source code 6 votes vote down vote up
/**
 * 设置发信人
 * 
 * @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;
	}
}
 
Example 6
Project: parabuild-ci   File: NotificationUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example 7
Project: webpage-update-subscribe   File: EmailServer.java   View source code 6 votes vote down vote up
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;
}
 
Example 8
Project: DiscussionPortal   File: SendMail.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 9
Project: theskeleton   File: TokenStoreServiceImpl.java   View source code 6 votes vote down vote up
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");
	}
}
 
Example 10
Project: spring-integration-dsl-samle   File: MailServiceImpl.java   View source code 6 votes vote down vote up
@Override
public void sendMessageOrderIsReady(String recipientEmail) {
    System.out.println("Sending e-mail to "+recipientEmail);
    Properties props = buildProperties();
    Session session = Session.getInstance(props, buildAuthenticator());
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject("Package ready to fly");
        message.setText("Your package is ready to fly!");

        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 12
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 13
Project: ats-framework   File: MimePackage.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 14
Project: sztw   File: MailCore.java   View source code 6 votes vote down vote up
/**
 *
 * @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;
}
 
Example 15
Project: uavstack   File: JavaMailAction.java   View source code 5 votes vote down vote up
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;
}
 
Example 16
Project: kettle_support_kettle8.0   File: Message.java   View source code 5 votes vote down vote up
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;
}
 
Example 17
Project: JavaToolKit   File: MailUtils.java   View source code 5 votes vote down vote up
/**
 * 验证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();
	}
}
 
Example 18
Project: cerebro   File: MailSenderImpl.java   View source code 5 votes vote down vote up
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;
}
 
Example 19
Project: HustEating   File: Mail.java   View source code 5 votes vote down vote up
/**
 * 创建一封反馈邮件
 * @param session
 * @param sendMail
 * @param detail
 * @return
 */
private MimeMessage createFeedBackMsg(Session session, String sendMail, String detail) throws UnsupportedEncodingException, MessagingException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sendMail, "吃在华科", "UTF-8"));
    message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]", this.name, "UTF-8"));
    message.setSubject("吃在华科用户反馈", "UTF-8");
    String content = UserStatus.getUserStatus().getName()+"\n"+detail;
    message.setContent(content, "text/html;charset=UTF-8");
    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}
 
Example 20
Project: sdudoc   File: MailUtil.java   View source code 5 votes vote down vote up
/** 发送密码重置的邮件 */
public static void sendResetPasswordEmail(User user) {
	String subject = "sdudoc密码重置提醒";
	String content = "您于" + DocUtil.getDateTime() + "在sdudoc找回密码,点击以下链接,进行密码重置:"
			+ "http://127.0.0.1:8080/sdudoc/resetPasswordCheck.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请密码重置,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		message.setSubject(subject);
		BodyPart mdp = new MimeBodyPart();
		mdp.setContent(content, "text/html;charset=utf8");
		Multipart mm = new MimeMultipart();
		mm.addBodyPart(mdp);
		message.setContent(mm);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 21
Project: solo-spring   File: MailService.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: MicroServiceDemo   File: AccountController.java   View source code 5 votes vote down vote up
public static boolean isValidEmailAddress(String email) {
    boolean valid = true;
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
    } catch (AddressException ex) {
        valid = false;
    }
    return valid;
}
 
Example 23
Project: AndroidKillerService   File: SimpleMailSender.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 24
Project: pathological-reports   File: EmailService.java   View source code 5 votes vote down vote up
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"));
	}
}
 
Example 25
Project: PTEAssistant   File: EamilReporter.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 26
Project: java-gps-tracking-server   File: MessageSenderConsumer.java   View source code 5 votes vote down vote up
/**
 *
 */
public MessageSenderConsumer() {
    try {
        this.production = new InternetAddress[]{new InternetAddress("[email protected]"), new InternetAddress("[email protected]"), new InternetAddress("[email protected]")};
        this.dev = new InternetAddress[]{new InternetAddress("[email protected]")};
    } catch (AddressException ex) {
        REG_LOGGER.fatal("AddressException", ex);
    }
}
 
Example 27
Project: iBase4J-Common   File: EmailSender.java   View source code 5 votes vote down vote up
/**
 * 设置发信人
 * 
 * @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;
	}
}
 
Example 28
Project: matrix-appservice-email   File: EmailEndPoint.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 29
Project: Parallator   File: MailSender.java   View source code 5 votes vote down vote up
public boolean send() throws Exception {
    Properties props = _setProperties();
    Session session = Session.getInstance(props, this);
    MimeMessage msg = new MimeMessage(session);
    msg.setSubject(subject);
    msg.setFrom(new InternetAddress("[email protected]"));
    msg.setRecipients(MimeMessage.RecipientType.TO, new InternetAddress[] {
            new InternetAddress("[email protected]")
    });
    msg.setSentDate(new Date());
    msg.setContent(multipart);
    Transport.send(msg);
    return true;
}
 
Example 30
Project: TITAN   File: EmailSender.java   View source code 5 votes vote down vote up
/**
 * @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;
}
 
Example 31
Project: Yidu   File: MailUtils.java   View source code 5 votes vote down vote up
/**
 * 发邮件处理
 * 
 * @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;

}
 
Example 32
Project: Java-for-Data-Science   File: ValidatingData.java   View source code 5 votes vote down vote up
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";
	}
}
 
Example 33
Project: Sound.je   File: EmailUtil.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 34
Project: Equella   File: EmailServiceImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 35
Project: plugin-password   File: PasswordResource.java   View source code 5 votes vote down vote up
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;
}
 
Example 36
Project: MailCopier   File: MailCopier.java   View source code 5 votes vote down vote up
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());
}
 
Example 37
Project: alfresco-repository   File: EmailServiceImplTest.java   View source code 5 votes vote down vote up
/**
 * MNT-9289
 * 
 * Change in case in email Subject causes DuplicateChildNodeNameException
 */
public void testCaseSensitivity() throws Exception
{
 NodeRef person = personService.getPerson(TEST_USER);
 String TEST_EMAIL="[email protected]";
 NodeRef testUserHomeFolder = (NodeRef)nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
    if(person == null)
    {
        logger.debug("new person created");
        Map<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ContentModel.PROP_USERNAME, TEST_USER);
        props.put(ContentModel.PROP_EMAIL, TEST_EMAIL);
        person = personService.createPerson(props);
    }
    
    nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL);

    Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true);
    if(!auths.contains(TEST_USER))
    {
        authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER);
    }
    
    String companyHomePathInStore = "/app:company_home"; 
    String storePath = "workspace://SpacesStore";
    StoreRef storeRef = new StoreRef(storePath);

    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);
    assertNotNull("company home is null", companyHomeNodeRef);
 
    String TEST_CASE_SENSITIVITY_SUBJECT = "Test (Mail)";
    String testUserHomeDBID = ((Long)nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID)).toString() + "@Alfresco.com";
 
    String from = TEST_EMAIL;
    String to = testUserHomeDBID;
    String content = "hello world";

    Session sess = Session.getDefaultInstance(new Properties());
    assertNotNull("sess is null", sess);
    SMTPMessage msg = new SMTPMessage(sess);
    InternetAddress[] toa =  { new InternetAddress(to) };
    
    EmailDelivery delivery = new EmailDelivery(to, from, null);

    msg.setFrom(new InternetAddress(TEST_EMAIL));
    msg.setRecipients(Message.RecipientType.TO, toa);
    msg.setContent(content, "text/plain");
 
    msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT);
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    msg.writeTo(bos1);
    InputStream is = IOUtils.toInputStream(bos1.toString());
    assertNotNull("is is null", is);
    SubethaEmailMessage m = new SubethaEmailMessage(is);  
    folderEmailMessageHandler.setOverwriteDuplicates(false);
    emailService.importMessage(delivery, m);
    
    QName safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT);
    List<ChildAssociationRef> assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
    assertEquals(1, assocs.size());
    
    msg.setSubject(TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase());
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    msg.writeTo(bos2);
    is = IOUtils.toInputStream(bos2.toString());
    assertNotNull("is is null", is);
    m = new SubethaEmailMessage(is);  
    folderEmailMessageHandler.setOverwriteDuplicates(false);
    emailService.importMessage(delivery, m);
    
    safeQName = QName.createQNameWithValidLocalName(NamespaceService.CONTENT_MODEL_1_0_URI, TEST_CASE_SENSITIVITY_SUBJECT.toUpperCase() +  "(1)");
    assocs = nodeService.getChildAssocs(testUserHomeFolder, ContentModel.ASSOC_CONTAINS, safeQName);
    assertEquals(1, assocs.size());
}
 
Example 38
Project: satisfy   File: EmailHelper.java   View source code 5 votes vote down vote up
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;
}
 
Example 39
Project: DDNS_Server   File: CreateServlet.java   View source code 5 votes vote down vote up
public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}
 
Example 40
Project: alfresco-repository   File: AbstractMailActionExecuterTest.java   View source code 5 votes vote down vote up
/**
 * Test for MNT-11079
 */
@Test
public void testSendingToUserWithMailAlikeName() throws IOException, MessagingException
{
    final String USER_1 = "[email protected]";
    final String USER_1_EMAIL = "[email protected]";

    try
    {
        createUser(USER_1, USER_1_EMAIL);

        Action mailAction = ACTION_SERVICE.createAction(MailActionExecuter.NAME);
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, "[email protected]");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TO_MANY, USER_1);

        mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, "Testing");
        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, "alfresco/templates/mail/test.txt.ftl");

        mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) getModel());

        ACTION_SERVICE.executeAction(mailAction, null);

        MimeMessage message = ACTION_EXECUTER.retrieveLastTestMessage();
        Assert.assertNotNull(message);
        Assert.assertEquals("Hello Jan 1, 1970", (String) message.getContent());
        Assert.assertEquals(1, message.getAllRecipients().length);
        javax.mail.internet.InternetAddress address = (InternetAddress) message.getAllRecipients()[0];
        Assert.assertEquals(USER_1_EMAIL, address.getAddress());
    }
    finally
    {
        // tidy up
        PERSON_SERVICE.deletePerson(USER_1);
    }
}