Java Code Examples for javax.mail.MessagingException#printStackTrace()

The following examples show how to use javax.mail.MessagingException#printStackTrace() . 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: AutoSendEmail.java    From AndroidTranslucentUI with Apache License 2.0 6 votes vote down vote up
/**
 * �����ʼ�
 */
private void sendEmail(String host,String account,String pwd){
	//��������
	try {
		this.message.setSentDate(new Date());
		this.message.setContent(this.multipart);
		this.message.saveChanges();
		Transport transport=session.getTransport("smtp");  
		transport.connect(host,account,pwd);  
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	} catch (MessagingException e) {
		errorMessage = "�����ʼ�ʧ��(�����ռ��������ַ�����糬ʱ):"+e.getMessage();
		e.printStackTrace();
	}
	
	
}
 
Example 2
Source File: EmailService.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void sendEmail(String email, String subjectline, String content) throws UnsupportedEncodingException{
    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"),
                Configurations.getConfigurationProperty("poc.cfg.property.smtp.fromName")));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(subjectline);

        if(Configurations.getConfigurationProperty("poc.cfg.property.email.type").equalsIgnoreCase("HTML")){
            message.setContent(content, "text/html; charset=utf-8");
        }
        else{
            message.setText(content);
        }

        Transport.send(message);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "POC-ERR-5001", ex.getLocalizedMessage());
    }
}
 
Example 3
Source File: MailService.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
public void sendAttachmentsMail(String toMail,String subject,String content,String filePath) {
 	MimeMessage message = sender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(formMail);
        helper.setTo(toMail);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = filePath.substring(filePath.lastIndexOf("/"));
        helper.addAttachment(fileName, file);
        sender.send(message);
        logger.info("发送给"+toMail+"带附件的邮件已经发送。");
    } catch (MessagingException e) {
        e.printStackTrace();
        logger.error("发送给"+toMail+"带附件的邮件时发生异常!", e);
    }
}
 
Example 4
Source File: ArdulinkMailMessageCountAdapter.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
public void messagesAdded(MessageCountEvent ev) {
    Message[] msgs = ev.getMessages();
    System.out.println("Got " + msgs.length + " new messages");

    for (int i = 0; i < msgs.length; i++) {
		try {
			manageMessage(msgs[i]);
		} catch (IOException ioex) { 
		    ioex.printStackTrace();	
		} catch (MessagingException mex) {
		    mex.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
 
Example 5
Source File: EmailUtils.java    From tools with MIT License 6 votes vote down vote up
/**
 * 发送普通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 6
Source File: AccessStructure.java    From jplag with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return A MimeMultipart object containing the zipped result files
 */
public MimeMultipart getResult() {

    File file = new File(JPLAG_RESULTS_DIRECTORY + File.separator
            + submissionID + getUsername() + ".zip");

    MimeMultipart mmp = new MimeMultipart();

    FileDataSource fds1 = new FileDataSource(file);
    MimetypesFileTypeMap mftp = new MimetypesFileTypeMap();
    mftp.addMimeTypes("multipart/zip zip ZIP");
    fds1.setFileTypeMap(mftp);

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(fds1));
        mbp.setFileName(file.getName());

        mmp.addBodyPart(mbp);
    } catch (MessagingException me) {
        me.printStackTrace();
    }
    return mmp;
}
 
Example 7
Source File: EmailAction.java    From spring-boot-examples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "html_with_template")
public String sendHtmlByTemplate(String msg, String email) {
    if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
        return "请输入要发送消息和目标邮箱";
    }

    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setFrom(sendName);
        messageHelper.setTo(email);
        messageHelper.setSubject("使用HTML模板文件发送邮件");

        Context context = new Context();
        context.setVariable("msg", msg);
        messageHelper.setText(templateEngine.process("EmailTemplate", context), true);
        mailSender.send(message);
        return "发送成功";
    } catch (MessagingException e) {
        e.printStackTrace();
        return "发送失败:" + e.getMessage();
    }
}
 
Example 8
Source File: ArdulinkMailMessageCountListener.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
public void messagesAdded(MessageCountEvent ev) {
    Message[] msgs = ev.getMessages();
	logger.info("Got {} new messages", msgs.length);

    for (int i = 0; i < msgs.length; i++) {
		try {
			manageMessage(msgs[i]);
		} catch (IOException ioex) { 
		    ioex.printStackTrace();	
		} catch (MessagingException mex) {
		    mex.printStackTrace();
		}
    }
}
 
Example 9
Source File: MBoxMessage.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String getMessageId() {
	String messageID = "";
	try {
		messageID = mimeMessage.getMessageID();
	} catch (MessagingException e) {
		System.err.println("MESSAGEID NOT FOUND");
		e.printStackTrace();
	}
	if (messageID==null || messageID.length()==0)
		System.err.println("MESSAGEID NULL OR ZERO LENGTH");
	return messageID;
}
 
Example 10
Source File: MailingService.java    From blog-tutorials with MIT License 5 votes vote down vote up
public void sendSimpleMail() {

    Message simpleMail = new MimeMessage(mailSession);

    try {
      simpleMail.setSubject("Hello World from Java EE!");
      simpleMail.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));

      MimeMultipart mailContent = new MimeMultipart();

      MimeBodyPart mailMessage = new MimeBodyPart();
      mailMessage.setContent("<p>Take a look at the <b>scecretMessage.txt</b> file</p>", "text/html; charset=utf-8");
      mailContent.addBodyPart(mailMessage);

      MimeBodyPart mailAttachment = new MimeBodyPart();
      DataSource source = new ByteArrayDataSource("This is a secret message".getBytes(), "text/plain");
      mailAttachment.setDataHandler(new DataHandler(source));
      mailAttachment.setFileName("secretMessage.txt");

      mailContent.addBodyPart(mailAttachment);
      simpleMail.setContent(mailContent);

      Transport.send(simpleMail);

      System.out.println("Message successfully send to: " + emailAddress);
    } catch (MessagingException e) {
      e.printStackTrace();
    }

  }
 
Example 11
Source File: WebEmail.java    From Autumn with GNU General Public License v2.0 5 votes vote down vote up
public void sendHtmlMailOnThymeleaf(String to){
    // Prepare the evaluation context
    final Context ctx = new Context();
    ctx.setVariable("username", "test");
    ctx.setVariable("link", "https://shuaijunlan.cn/autumn-cms/index.do");


    // Prepare message using a Spring helper
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        messageHelper.setFrom(mailMessage.getFrom());
        messageHelper.setSubject("激活邮件"); //主题
        messageHelper.setTo(to); //发送给
        messageHelper.setCc(mailMessage.getFrom()); //抄送


        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process("register-auth", ctx);
        mimeMessage.setContent(htmlContent, "text/html;charset=utf-8");
        // send mail
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        e.printStackTrace();
    }


}
 
Example 12
Source File: IMAPAdapter.java    From hana-native-adapters with Apache License 2.0 5 votes vote down vote up
@Override
public void poll() {
	try {
		if (inbox != null) {
			inbox.getMessageCount();
		}
	} catch (MessagingException e) {
		e.printStackTrace();
	}
}
 
Example 13
Source File: MailerIT.java    From jeeshop with Apache License 2.0 5 votes vote down vote up
@Test
public void sendMail() throws Exception{
    Mailer mailer = container.instance().select(Mailer.class).get();
    try {
        mailer.sendMail("Test Subject", "[email protected]", "<h1>Hello</h1>");
    } catch (MessagingException e) {
        e.printStackTrace();
        fail();
    }

    assertThat(server.getReceivedMessages().length).isEqualTo(1);
    assertThat(server.getReceivedMessages()[0].getSubject()).isEqualTo("Test Subject");
}
 
Example 14
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 判断邮件是否已读 
 *  
 * @param msg   邮件内容 
 * @return 如果邮件已读返回true,否则返回false 
 */ 
public static boolean isSeen(MimeMessage msg){ 
	try { 
		return msg.getFlags().contains(Flags.Flag.SEEN); 
	} catch (MessagingException e) { 
		e.printStackTrace(); 
	} 
	return false; 
}
 
Example 15
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
  * 删除邮件 
  * @param messages  messages
  */ 
 public static void delete(Message ...messages){   
     for (int i = 0, count = messages.length; i < count; i++) {   
         Message message = messages[i]; 
         String subject; 
try { 
	subject = message.getSubject(); 
          message.setFlag(Flags.Flag.DELETED, true); 
          log.warn("[删除邮件][subject:{}]",subject); 
} catch (MessagingException e) { 
	e.printStackTrace(); 
} 
     } 
 }
 
Example 16
Source File: EmailSenderTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testEmailWithAttachment() {
    EmailSender sender = new EmailSender();
    try {
        File file = new File("pom.xml");
        String absolutePath = file.getAbsolutePath();
        sender.sendMailWithAttachment("[email protected]", "with attachment", "This is message body", absolutePath);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example 17
Source File: SimpleMailSender.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 以文本格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件的信息
 */
public boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(),
                mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session
            .getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 18
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 以文本格式发送邮件
 *
 * @param mailInfo 待发送的邮件的信息
 */
public static boolean sendTextMail(MailSenderInfo mailInfo) {

    try {

        // 设置一些通用的数据
        Message mailMessage = setCommon(mailInfo);

        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);

        // 发送邮件
        Transport.send(mailMessage);

        return true;

    } catch (MessagingException ex) {

        ex.printStackTrace();
    }

    return false;
}
 
Example 19
Source File: EmailLogServlet.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public boolean sendLog(String host, String userId, String password,
        String to, String from, String subject, String message,
        File filename) {
    boolean success = true;
    System.out.println("host: " + host);
    System.out.println("userId: " + userId);
    // Fortify Mod: commented out clear text password.
    // System.out.println("password: " + password);
    System.out.println("to: " + to);
    System.out.println("from: " + from);
    System.out.println("subject: " + subject);
    System.out.println("message: " + message);
    System.out.println("filename: " + filename.getName());
    System.out.println("filename: " + filename.getAbsolutePath());

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");

    Session session = Session.getInstance(props, null);
    session.setDebug(true);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(message);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        // connect to the transport
        Transport trans = session.getTransport("smtp");
        trans.connect(host, userId, password);

        // send the message
        trans.sendMessage(msg, msg.getAllRecipients());

        // smtphost
        trans.close();

    } catch (MessagingException mex) {
        success = false;
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
    return success;
}
 
Example 20
Source File: SendEmailController.java    From oncokb with GNU Affero General Public License v3.0 4 votes vote down vote up
private static Boolean sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        return true;
    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }

    return false;
}