コード例 #1
0
ファイル: EmailUtils.java プロジェクト: zkpking/DemoWeb08
  /**
   * 发送邮件 (暂时只支持163邮箱发送)
   *
   * @param fromEmail 发送邮箱
   * @param toEmail 接收邮箱
   * @param emailName 163邮箱登录名
   * @param emailPassword 密码
   * @param title 发送主题
   * @param centent 发送内容
   * @throws Exception
   */
  public static void sendMail(
      String fromEmail,
      String toEmail,
      String emailName,
      String emailPassword,
      String title,
      String centent)
      throws Exception {

    Properties properties = new Properties(); // 创建Properties对象
    properties.setProperty("mail.transport.protocol", "smtp"); // 设置传输协议
    properties.put("mail.smtp.host", "smtp.163.com"); // 设置发信邮箱的smtp地址
    properties.setProperty("mail.smtp.auth", "true"); // 验证
    Authenticator auth = new AjavaAuthenticator(emailName, emailPassword); // 使用验证,创建一个Authenticator
    Session session =
        Session.getDefaultInstance(properties, auth); // 根据Properties,Authenticator创建Session
    Message message = new MimeMessage(session); // Message存储发送的电子邮件信息
    message.setFrom(new InternetAddress(fromEmail));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); // 设置收信邮箱
    // 指定邮箱内容及ContentType和编码方式
    message.setContent(centent, "text/html;charset=utf-8");
    message.setSubject(title); // 设置主题
    message.setSentDate(new Date()); // 设置发信时间
    Transport.send(message); // 发送
  }
コード例 #2
0
ファイル: AlertEmailer.java プロジェクト: rmachedo/MEater
  /**
   * Sends an email using the given parameters.
   *
   * @param smtp The SMTP server to send from
   * @param from The from-address
   * @param to The to-address
   * @param subj The subject line
   * @param body The message body
   * @throws MessagingException If the email fails to send
   */
  public static void send(
      final String smtp, final String from, final String to, final String subj, final String body)
      throws MessagingException {
    // Silently quit if we are missing any required email information
    if (smtp == null
        || from == null
        || to == null
        || smtp.isEmpty()
        || from.isEmpty()
        || to.isEmpty()) return;

    // Set the host smtp address
    final Properties mailProps = new Properties();
    mailProps.put("mail.smtp.host", smtp);

    // create some properties and get the default Session
    final Session session = Session.getDefaultInstance(mailProps, null);

    // create a message
    final Message msg = new MimeMessage(session);

    // set the from and to address
    final InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    final InternetAddress addressTo = new InternetAddress(to);
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // set the subject and body
    msg.setSubject(subj);
    msg.setContent(body, "text/plain");

    // send the email message
    Transport.send(msg);
  }
コード例 #3
0
ファイル: Mail.java プロジェクト: RainerJava/codigocerto
  private Message gerarMensagem(String emissor, String destino, String assunto) {
    Message mensagem = new MimeMessage(_sessao);
    try {
      mensagem.setFrom(new InternetAddress(emissor));
      mensagem.setRecipient(Message.RecipientType.TO, new InternetAddress(destino));
      mensagem.setSubject(assunto);

      if (_existemAnexos) {
        MimeBodyPart conteudo = new MimeBodyPart();
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          conteudo.setContent(_texto, TipoConteudo.HTML);
        } else {
          conteudo.setContent(_texto, TipoConteudo.TEXTO);
        }
        Multipart divisoesConteudo = new MimeMultipart();
        divisoesConteudo.addBodyPart(conteudo);
        inserirAnexosArquivo(divisoesConteudo);
        inserirAnexosConteudo(divisoesConteudo);
        mensagem.setContent(divisoesConteudo);
      } else {
        if (_tipoMensagem.equals(Conteudo.HTML)) {
          mensagem.setContent(_texto, TipoConteudo.HTML);
        } else {
          mensagem.setContent(_texto, TipoConteudo.TEXTO);
        }
      }

    } catch (MessagingException ex) {
      Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
      mensagem = null;
    }

    return mensagem;
  }
コード例 #4
0
ファイル: Mail.java プロジェクト: joensen/Aarhus-Cafekirke
  public boolean send() {

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
    } catch (AddressException e) {
      e.printStackTrace();
      return false;
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setText(text);

      Transport.send(simpleMessage);
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #5
0
 /**
  * 以文本格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendTextMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MailAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   if (mailInfo.isValidate()) {
     // 如果需要身份认证,则创建一个密码验证器
     authenticator = new MailAuthenticator(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;
 }
コード例 #6
0
ファイル: MailUtil.java プロジェクト: yyyfan/xkg
  public static void sendMailBySea(
      String formAddress, String toAddress, String title, String content) throws Exception {

    Properties p = new Properties();
    p.put("mail.smtp.host", "smtp.sina.com");
    p.put("mail.smtp.port", "25");
    p.put("mail.smtp.auth", "true");
    Authenticator authenticator =
        new Authenticator() {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("*****@*****.**", "password");
          }
        };
    Session sendMailSession = Session.getDefaultInstance(p, authenticator);
    Message mailMessage = new MimeMessage(sendMailSession);
    Address from = new InternetAddress(formAddress);
    mailMessage.setFrom(from);
    Address to = new InternetAddress(toAddress); // 设置接收人员
    mailMessage.setRecipient(Message.RecipientType.TO, to);
    mailMessage.setSubject(title); // 设置邮件标题
    mailMessage.setText(content); // 设置邮件内容
    // 发送邮件
    Transport.send(mailMessage);
  }
コード例 #7
0
  public static void main(String[] args) throws Exception {

    final Properties props = new Properties();
    props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

    Session session =
        Session.getInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
              }
            });

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(props.getProperty("address.sender")));
    message.setRecipient(
        Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
    message.setSubject("Test JavaMail");

    message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

    Transport.send(message);

    log.info("Message was sent");
  }
コード例 #8
0
ファイル: Mailer.java プロジェクト: cuantico/OnlineAutoParts
  public synchronized void send() throws MessagingException {

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.port", SMTP_PORT_NUMBER);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtps.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", SMTP_HOST_NAME);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT_NUMBER);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.quitwait", "false");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    Message simpleMessage = new MimeMessage(session);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    InternetAddress ccAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
      if (cc != null && cc.length() > 0) ccAddress = new InternetAddress(cc);
    } catch (AddressException e) {
      e.printStackTrace();
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      if (ccAddress != null) simpleMessage.setRecipient(RecipientType.CC, ccAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setContent(text, contentType);
      // simpleMessage.setText(text);
      Transport.send(simpleMessage);
    } catch (MessagingException e) {
      throw e;
    }
  }
コード例 #9
0
  public void sendMail(String from, String to, String subject, String message) {

    Properties props = new Properties();

    // para SERVIDOR PROXY descomente essa parte e atribua as propriedades
    /*
                 props.setProperty("proxySet","true");
                 props.setProperty("socksProxyHost","192.168.155.1"); // IP do Servidor Proxy
                 props.setProperty("socksProxyPort","1080");  // Porta do servidor Proxy
    */

    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailSMTPServer);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.user", from);
    props.put("mail.debug", "false");
    props.put("mail.smtp.port", mailSMTPServerPort); // porta
    props.put("mail.smtp.socketFactory.port", mailSMTPServerPort); // mesma porta para o socket
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SimpleAuth auth = null;
    auth = new SimpleAuth("*****@*****.**", "****");

    Session session = Session.getDefaultInstance(props, auth);
    //		session.setDebug(true); //Habilita o LOG das ações executadas durante o envio do email

    Message msg = new MimeMessage(session);

    try {
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setFrom(new InternetAddress(from));
      msg.setSubject(subject);
      message += "\n\n Enviado por: " + from;
      msg.setContent(message, "text/plain");
    } catch (Exception e) {
      System.out.println(">> Erro: Completar Mensagem");
      e.printStackTrace();
    }

    Transport tr;
    try {
      tr = session.getTransport("smtp"); // define smtp para transporte
      tr.connect(mailSMTPServer, "*****@*****.**", "***");
      msg.saveChanges(); // don't forget this
      // envio da mensagem
      tr.sendMessage(msg, msg.getAllRecipients());
      tr.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #10
0
ファイル: SendMail.java プロジェクト: orgranktest/webapp
  public static int sendMail(String toAddr, String ccAddr, String mailTitle, String mailConcept) {
    Session s = Session.getInstance(SendMail.props, null);
    s.setDebug(false);

    Message message = new MimeMessage(s);
    try {
      Address from = new InternetAddress(SendMail.SenderEmailAddr);
      message.setFrom(from);
      Address to = new InternetAddress(toAddr);
      message.setRecipient(Message.RecipientType.TO, to);
      if (ccAddr != null && ccAddr != "") {
        Address cc = new InternetAddress(ccAddr);
        message.setRecipient(Message.RecipientType.CC, cc);
      }

      message.setSubject(mailTitle);
      Multipart mainPart = new MimeMultipart();
      BodyPart html = new MimeBodyPart();
      html.setContent(mailConcept, "text/html;charset=ISO-8859-1");
      mainPart.addBodyPart(html);
      message.setContent(mainPart);
      message.setSentDate(new Date());
      message.saveChanges();

      Transport transport = s.getTransport(SendMail.TransprotType);
      transport.connect(SendMail.SMTPServerName, SendMail.SMTPUserName, SendMail.SMTPPassword);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();

      //			System.out.println("发送邮件,邮件地址:"+toAddr);
      //			System.out.println("发送邮件,邮件地址:"+ccAddr);
      //			System.out.println("标题:"+mailTitle);
      //			System.out.println("内容:"+mailConcept);
      System.out.println("Email Send Success!");
      return 1;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      return -1;
    }
  }
コード例 #11
0
  public static boolean SendMail(
      String from, String to, String cc, String subject, String content) {
    Properties props = System.getProperties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.failBack", "false");
    props.put("mail.smtp.quitwait", "false");

    try {
      Session session =
          Session.getInstance(
              props,
              new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("*****@*****.**", "3003191114");
                }
              });
      Message message = new MimeMessage(session);
      Address fromAdd = new InternetAddress(to);
      Address toAdd = new InternetAddress(to);
      Address ccAdd = new InternetAddress(cc);

      message.setFrom(fromAdd);
      message.setRecipient(Message.RecipientType.TO, toAdd);
      message.setRecipient(Message.RecipientType.CC, ccAdd);

      MimeBodyPart messagePart = new MimeBodyPart();
      MimeMultipart mutilPart = new MimeMultipart();

      mutilPart.addBodyPart(messagePart);

      messagePart.setText(content, "utf-8");
      messagePart.setHeader("Content-Type", "text/html;character=\"utf-8\"");
      messagePart.setHeader("Content-Transfer-Encoding", "quoted-printable");

      message.setSubject(subject);
      message.setContent(mutilPart);
      message.setSentDate(new Date());

      Transport.send(message);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #12
0
 @Test
 public void testUploadingOfAEmail() throws Exception {
   TransportInterface transport =
       new GmailMessageUploader(
           new DefaultFolderManagement(),
           "ibatis/another folder2",
           new Credentials(TestOptions.username, TestOptions.password));
   Properties sessionProperties = new Properties();
   Session session = Session.getInstance(sessionProperties);
   Message msg = new MimeMessage(session);
   msg.setFrom(new InternetAddress("*****@*****.**"));
   msg.setRecipient(RecipientType.TO, new InternetAddress("*****@*****.**"));
   msg.setText("Tes message here");
   transport.uploadMessage(new EmailMessage(msg));
 }
コード例 #13
0
  public boolean sendEmailSSL(String to, String subject, String body) {

    System.out.println("sendEmailSSL, to:" + to + " / subject: " + subject + "body: " + body);

    usernameSSL = sessionSSL.getProperty("mail.smtp.user");
    passwordSSL = sessionSSL.getProperty("mail.smtp.password");

    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", sessionSSL.getProperty("mail.smtp.host"));
      props.put(
          "mail.smtp.socketFactory.port", sessionSSL.getProperty("mail.smtp.socketFactory.port"));
      props.put(
          "mail.smtp.socketFactory.class", sessionSSL.getProperty("mail.smtp.socketFactory.class"));
      props.put("mail.smtp.auth", sessionSSL.getProperty("mail.smtp.auth"));
      props.put("mail.smtp.port", sessionSSL.getProperty("mail.smtp.port"));
      props.put("debug", sessionSSL.getProperty("debug"));

      String fromAddress = sessionSSL.getProperty("mail.smtp.from");
      System.out.println("user/password: "******"/" + passwordSSL);

      sessionSSL =
          Session.getDefaultInstance(
              props,
              new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(usernameSSL, passwordSSL);
                }
              });

      sessionSSL.setDebug(props.getProperty("debug") == "true");

      Message message = new MimeMessage(sessionSSL);

      message.setFrom(new InternetAddress(fromAddress));
      message.setRecipient(RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);
      message.setContent(body, "text/plain");
      System.out.println("Send email");
      Transport.send(message);
      System.out.println("email sent");
      return true;
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return false;
    }
  }
コード例 #14
0
 /**
  * 以HTML格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendHtmlMail(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());
     // Message.RecipientType.TO属性表示接收者的类型为TO
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
     Multipart mainPart = new MimeMultipart();
     // 创建一个包含HTML内容的MimeBodyPart
     BodyPart html = new MimeBodyPart();
     // 设置HTML内容
     html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
     mainPart.addBodyPart(html);
     // 将MiniMultipart对象设置为邮件内容
     mailMessage.setContent(mainPart);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
コード例 #15
0
ファイル: Mailer.java プロジェクト: aravindpl/sales_tax
  public void send(final String from, final String to, final String subject, final String content)
      throws AddressException, MessagingException {
    Session session = Session.getDefaultInstance(props, null);

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    String[] toAddresses = to.split(",");
    for (int i = 0; i < toAddresses.length; i++) {
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses[i]));
    }
    msg.setSubject(subject);
    msg.setText(content);

    if (auth) {
      Transport transport = session.getTransport("smtp");
      transport.connect(host, port, username, password);
      msg.saveChanges();
      transport.sendMessage(msg, msg.getAllRecipients());
      transport.close();
    } else {
      Transport.send(msg);
    }
  }
コード例 #16
0
ファイル: SendMessage.java プロジェクト: FRA-UAS/Mailer
  private void mailSend() {

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.setProperty("mail.smtp.port", "587");
    Authenticator auth =
        new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, userPassword);
          }
        };
    Session session = Session.getInstance(properties, auth);
    Message message = new MimeMessage(session);
    String subject = subjectField.getText();
    String from = "338399047";
    String mailMessage = referenceTextArea.getText();

    String to = "";
    to = toField.getText();
    boolean validateCc = true;
    boolean validateBcc = true;
    boolean wrongMail = true;

    if (ccField.getText().isEmpty() && bccField.getText().isEmpty()) {

      validateCc = true;
      validateBcc = true;
      wrongMail = false;

    } else if (!ccField.getText().isEmpty() && bccField.getText().isEmpty()) {

      if (countMail(ccField.getText()) == 1) {
        try {
          InternetAddress ccAddress = new InternetAddress(ccField.getText());
          ccAddress.validate();
          validateCc = true;
          validateBcc = false;
        } catch (AddressException e1) {
          JOptionPane.showMessageDialog(
              null, "Please enter a correct mail in the cc field!\n Or leave the ccfield empty!");
          wrongMail = true;
          validateCc = false;
        }

        if (validateCc) {
          wrongMail = false;
        }

      } else {
        wrongMail = false;
      }

    } else if (ccField.getText().isEmpty() && !bccField.getText().isEmpty()) {

      if (countMail(bccField.getText()) == 1) {

        try {
          InternetAddress bccAddress = new InternetAddress(bccField.getText());

          bccAddress.validate();

          validateBcc = true;
          validateCc = false;
        } catch (AddressException e1) {
          JOptionPane.showMessageDialog(
              null, "Please enter a correct mail in the bcc field!\n Or leave the bccfield empty!");
          wrongMail = true;
          validateBcc = false;
        }

        if (validateBcc) {
          wrongMail = false;
        }

      } else {
        System.out.println("??? 1");
        wrongMail = false;
      }

    } else if (!ccField.getText().isEmpty() && !bccField.getText().isEmpty()) {
      if (countMail(ccField.getText()) == 1 && countMail(bccField.getText()) == 1) {

        try {
          InternetAddress ccAddress = new InternetAddress(ccField.getText());
          ccAddress.validate();
          validateCc = true;

        } catch (AddressException e1) {
          validateCc = false;
        }

        try {
          InternetAddress bccAddress = new InternetAddress(bccField.getText());
          bccAddress.validate();
          validateBcc = true;
        } catch (AddressException e1) {
          validateBcc = false;
        }

        if (validateBcc && validateCc) {
          wrongMail = false;

        } else {
          JOptionPane.showMessageDialog(
              null,
              "Please enter a correct mail in the bcc and cc field!\n Or leave both fields empty!");

          wrongMail = true;
        }

      } else {
        System.out.println("??? 2");
        wrongMail = false;
      }
    }

    SendMessage objectAddress = this;

    if (!wrongMail) {

      try {
        message.setSubject(subject);
        message.setFrom(new InternetAddress(from, "JavaProjekt"));
        message.setText(mailMessage);

        if (objectAddress.countMail(to) == 1) {
          message.setRecipient(RecipientType.TO, new InternetAddress(to));

        } else if (countMail(to) > 1) {

          InternetAddress[] addressArray = this.createInternetAddressArray(to, toList); // guck
          message.setRecipients(RecipientType.TO, addressArray);
        }

        if (countMail(ccField.getText()) > 1) {

          message.setRecipients(
              RecipientType.CC, this.createInternetAddressArray(ccField.getText(), ccList));
          validateCc = false;
        }

        if (countMail(bccField.getText()) > 1 && countMail(ccField.getText()) == 1) {
          validateCc = false;
        }

        if (!ccField.getText().isEmpty() && validateCc) {
          message.setRecipient(RecipientType.CC, new InternetAddress(ccField.getText()));
        }

        System.out.println("FIRST TRY" + validateBcc);

        if (countMail(bccField.getText()) > 1) {

          System.out.println("TEST 2");
          message.setRecipients(
              RecipientType.BCC, this.createInternetAddressArray(bccField.getText(), bccList));
          validateBcc = false;
        }

        System.out.println("SECOND TRY" + validateBcc);

        if (countMail(ccField.getText()) > 1 && countMail(bccField.getText()) == 1) {
          validateBcc = false;
        }

        if (!bccField.getText().isEmpty() && validateBcc) {
          message.setRecipient(RecipientType.BCC, new InternetAddress(bccField.getText()));
          System.out.println("flop");
        }
        System.out.println("THIRD TRY");

        Transport.send(message);

        if (wrongMails.isEmpty()) {
          JOptionPane.showMessageDialog(null, "Your E-Mail was sent.");

        } else {

          JOptionPane.showMessageDialog(
              null,
              "Your E-Mail was sent except of following emails: \n"
                  + wrongMails
                  + "\n"
                  + "Please enter your email addresses in a corect format!\nFor example: [email protected]",
              "Warning!",
              JOptionPane.WARNING_MESSAGE);

          wrongMails = "";
          wrongMailsStringBuilder = new StringBuilder();
        }
        System.out.println("Finished!");

      } catch (MessagingException | UnsupportedEncodingException e) {

      }
    }
  }
コード例 #17
0
  public boolean sendEmailSSL_HTML(String to, String subject, String body) {

    System.out.println("sendEmailSSL_HTML, to:" + to + " / subject: " + subject + "body: " + body);

    usernameSSL = sessionSSL.getProperty("mail.smtp.user");
    passwordSSL = sessionSSL.getProperty("mail.smtp.password");

    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", sessionSSL.getProperty("mail.smtp.host"));
      props.put(
          "mail.smtp.socketFactory.port", sessionSSL.getProperty("mail.smtp.socketFactory.port"));
      props.put(
          "mail.smtp.socketFactory.class", sessionSSL.getProperty("mail.smtp.socketFactory.class"));
      props.put("mail.smtp.auth", sessionSSL.getProperty("mail.smtp.auth"));
      props.put("mail.smtp.port", sessionSSL.getProperty("mail.smtp.port"));
      props.put("debug", sessionSSL.getProperty("debug"));

      String fromAddress = sessionSSL.getProperty("mail.smtp.from");
      System.out.println("user/password: "******"/" + passwordSSL);

      sessionSSL =
          Session.getDefaultInstance(
              props,
              new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(usernameSSL, passwordSSL);
                }
              });

      sessionSSL.setDebug(props.getProperty("debug") == "true");

      Message message = new MimeMessage(sessionSSL);

      message.setFrom(new InternetAddress(fromAddress));
      message.setRecipient(RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);

      // Create a MimeMultipart instance with an alternative sub-type.
      // A multi-part message consists of multiple parts, in this case an HTML and a text message
      // (other possible parts are file attachments).
      // The alternative sub-type indicates that the multiple message parts are alternative versions
      // of the same content.

      Multipart multipart = new MimeMultipart("alternative");

      // Create a MimeBodyPart instance to contain the text body part

      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(body + "(textcontent)");

      // Create a MimeBodyPart instance to contain the HTML body part.
      // Order is important, the preferred format of an alternative multi-part message should be
      // added last.

      MimeBodyPart htmlPart = new MimeBodyPart();
      String htmlContent = "<html><h1>Hi</h1><p>" + body + "(htmlcontent)" + "</p></html>";
      htmlPart.setContent(htmlContent, "text/html");

      // Add both MimeBodyPart instances to the MimeMultipart instance and set the MimeMultipart
      // instance as the MimeMessage.

      multipart.addBodyPart(textPart);
      multipart.addBodyPart(htmlPart);
      message.setContent(multipart);

      System.out.println("Send email");
      Transport.send(message);
      System.out.println("email sent");
      return true;
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return false;
    }
  }