Java Code Examples for com.sun.mail.smtp.SMTPTransport#connect()

The following examples show how to use com.sun.mail.smtp.SMTPTransport#connect() . 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: EMail.java    From TakServer with GNU General Public License v2.0 7 votes vote down vote up
public static void send(String to, String sub, String msg) {
    Properties prop = System.getProperties();
    prop.put("mail.smtps.host", host);
    prop.put("mail.smtps.auth", "true");
    Session session = Session.getInstance(prop);
    
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(sub);
        message.setText(msg);
        
        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
        t.connect(host, user, password);
        t.sendMessage(message, message.getAllRecipients());
        t.close();
        
        System.out.println("Email sent to "+to);
    } catch (MessagingException ex) {
        Logger.getLogger(EMail.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 2
Source File: SendingMailThroughGmailSMTPServer.java    From hellokoding-courses with MIT License 6 votes vote down vote up
void sendMail(String smtpServerHost, String smtpServerPort,  String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", smtpServerPort);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        SMTPTransport transport = new SMTPTransport(session, null);
        transport.connect(smtpServerHost, smtpUserName, null);
        transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
}
 
Example 3
Source File: ForgotPassword.java    From ShoppingCartinJava with MIT License 5 votes vote down vote up
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

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

    // -- Create a new message --
    final MimeMessage msg = new MimeMessage(session);

    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());      
    t.close();
}
 
Example 4
Source File: MailDelivrerToHost.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void connect(HostAddress outgoingMailServer, SMTPTransport transport) throws MessagingException {
    if (configuration.getAuthUser() != null) {
        transport.connect(outgoingMailServer.getHostName(), configuration.getAuthUser(), configuration.getAuthPass());
    } else {
        transport.connect();
    }
}
 
Example 5
Source File: EmailUtil.java    From kspl-selenium-helper with GNU General Public License v3.0 5 votes vote down vote up
private void send(Message msg) throws MessagingException
{
  SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
  try
  {
    t.connect(this.getHost(), this.getFrom(), this.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
  } finally
  {
    System.out.println("Response: " + t.getLastServerResponse());
    t.close();
  }
}
 
Example 6
Source File: SMTPCommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void mailSenderEmpty() throws IOException, MessagingException {
    Session smtpSession = greenMail.getSmtp().createSession();
    SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);

    try {
        Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport
        smtpTransport.connect(smtpSocket);
        assertThat(smtpTransport.isConnected(), is(equalTo(true)));
        smtpTransport.issueCommand("MAIL FROM: <>", -1);
        assertThat("250 OK", equalToCompressingWhiteSpace(smtpTransport.getLastServerResponse()));
    } finally {
        smtpTransport.close();
    }
}
 
Example 7
Source File: SMTPCommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void authLogin() throws IOException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();
    SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);
    try {
        Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport
        smtpTransport.connect(smtpSocket);
        assertThat(smtpTransport.isConnected(), is(equalTo(true)));

        // Should fail, as user does not exist
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_CREDENTIALS_INVALID));

        // Try again but create user
        greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass");
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_SUCCEDED));
    } finally {
        smtpTransport.close();
    }
}
 
Example 8
Source File: SMTPCommandTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void mailSenderAUTHSuffix() throws IOException, MessagingException {
    Session smtpSession = greenMail.getSmtp().createSession();
    SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);

    try {
        Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport
        smtpTransport.connect(smtpSocket);
        assertThat(smtpTransport.isConnected(), is(equalTo(true)));
        smtpTransport.issueCommand("MAIL FROM: <[email protected]> AUTH <>", -1);
        assertThat("250 OK", equalToCompressingWhiteSpace(smtpTransport.getLastServerResponse()));
    } finally {
        smtpTransport.close();
    }
}
 
Example 9
Source File: SendEmailSmtp.java    From opentest with MIT License 4 votes vote down vote up
@Override
public void run() {
    String server = this.readStringArgument("server");
    String subject = this.readStringArgument("subject");
    String body = this.readStringArgument("body");
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    String to = this.readStringArgument("to");
    Integer port = this.readIntArgument("port", 25);
    Boolean useTls = this.readBooleanArgument("useTls", true);
    String cc = this.readStringArgument("cc", null);
    String from = this.readStringArgument("from", "[email protected]");

    try {
        Properties prop = System.getProperties();
        prop.put("mail.smtp.host", server);
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.port", port.toString());

        Session session = Session.getInstance(prop, null);
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (cc != null) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }

        msg.setSubject(subject);
        msg.setText(body);
        msg.setSentDate(new Date());

        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(useTls);
        transport.connect(server, userName, password);
        transport.sendMessage(msg, msg.getAllRecipients());

        transport.close();
    } catch (Exception exc) {
        throw new RuntimeException("Failed to send email", exc);
    }
}
 
Example 10
Source File: EmailSmtpConnector.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));

        // We must encode our headers ourselves as we have no guarantee that they were in the provided data.
        // This is required to support UTF-8 characters from user display names or room names in the subject header per example
        Enumeration<Header> headers = msg.getAllHeaders();
        while (headers.hasMoreElements()) {
            Header header = headers.nextElement();
            msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue()));
        }

        msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent));
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");

        if (cfg.getTls() < 3) {
            transport.setStartTLS(cfg.getTls() > 0);
            transport.setRequireStartTLS(cfg.getTls() > 1);
        }

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) {
            log.info("Not using SMTP authentication");
            transport.connect();
        } else {
            log.info("Using SMTP authentication");
            transport.connect(cfg.getLogin(), cfg.getPassword());
        }

        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}