Search in sources :

Example 51 with Session

use of javax.mail.Session in project smartmodule by carozhu.

the class JavaEmail method sendEmailBUGForDevloper.

public static void sendEmailBUGForDevloper(String formApp, Throwable e, String email, String emailPassword) throws AddressException, MessagingException {
    Properties properties = new Properties();
    // Send mail	// protocol
    properties.setProperty("mail.transport.protocol", "smtp");
    // Need to verify
    properties.setProperty("mail.smtp.auth", "true");
    //Background debug mode
    properties.setProperty("mail.debug", "true");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.host", "smtp.qq.com");
    properties.put("mail.smtp.port", "220");
    MyAuthenticator smyauth = new MyAuthenticator(email, emailPassword);
    // setup process output messages sent
    Session session = Session.getInstance(properties, smyauth);
    // debug mode
    session.setDebug(true);
    // Email message
    Message messgae = new MimeMessage(session);
    // set sender
    messgae.setFrom(new InternetAddress(email));
    // set the messgae content
    messgae.setText(getErrorInfoFromException(e));
    System.out.println(getErrorInfoFromException(e));
    Date now = new Date();
    //可以方便地修改日期格式
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String hehe = dateFormat.format(now);
    // set the message subject
    messgae.setSubject("author:caro-->recv" + formApp + "   异常反馈,时间:" + hehe);
    // Send e-mail
    Transport tran = session.getTransport();
    // tran.connect("smtp.sohu.com", 25, "xxx@sohu.com", "xxxx");//sohu-mail
    // server to connect to
    // tran.connect("smtp.sina.com", 25, "xxx@sina.cn",
    // "xxxxxxx");//Sina-mail server to connect to
    // tran.connect("smtp.qq.com", 25, "xxx@qq.com", "xxxx");//qq-mail
    // server to connect to
    tran.connect("smtp.qq.com", 25, email, emailPassword);
    // Set// mail// recipient (email)  test:2376323219@qq.com  452262448@qq.com  1025807062@qq.com
    tran.sendMessage(messgae, new Address[] { new InternetAddress("1025807062@qq.com") });
    tran.close();
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Transport(javax.mail.Transport) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Session(javax.mail.Session)

Example 52 with Session

use of javax.mail.Session in project ddf by codice.

the class SmtpClientImplITCase method testSend.

@Test
public void testSend() throws IOException, MessagingException, ExecutionException, InterruptedException {
    int port = findAvailablePort();
    SimpleSmtpServer server = SimpleSmtpServer.start(port);
    SmtpClientImpl emailService = new SmtpClientImpl();
    emailService.setHostName(HOSTNAME);
    emailService.setPortNumber(port);
    Session session = emailService.createSession();
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
    mimeMessage.setSubject(SUBJECT);
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(BODY);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);
    emailService.send(mimeMessage).get();
    server.stop();
    assertThat(server.getReceivedEmailSize(), is(1));
    Iterator emailIterator = server.getReceivedEmail();
    SmtpMessage email = (SmtpMessage) emailIterator.next();
    assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
    assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
    assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
    assertThat(email.getBody(), containsString(BODY));
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SmtpMessage(com.dumbster.smtp.SmtpMessage) SimpleSmtpServer(com.dumbster.smtp.SimpleSmtpServer) Iterator(java.util.Iterator) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) Test(org.junit.Test)

Example 53 with Session

use of javax.mail.Session in project ddf by codice.

the class FeedbackApplication method init.

@Override
public void init() {
    post("/feedback", APPLICATION_JSON, (req, res) -> {
        if (StringUtils.isNotEmpty(emailDestination)) {
            FeedbackRequest feedback = parseFeedbackRequest(req.body());
            feedback.setAuthUsername(getCurrentUser());
            String emailSubject = getEmailSubject(feedback);
            String emailBody = getEmailBody(feedback);
            if (emailBody != null) {
                emailBody = emailBody.replaceAll("\\\\n", "\n");
            }
            Session emailSession = smtpClient.createSession();
            MimeMessage message = new MimeMessage(emailSession);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailDestination));
            message.setSubject(emailSubject);
            message.setContent(emailBody, "text/html; charset=utf-8");
            smtpClient.send(message);
            res.body("{}");
            res.status(200);
            return res;
        } else {
            res.status(500);
            res.body("No destination email configured, feedback cannot be submitted.");
            LOGGER.debug("Feedback submission failed, destination email is not configured.");
            return res;
        }
    });
    exception(Exception.class, (e, request, response) -> {
        response.status(500);
        response.body("Error submitting feedback");
        LOGGER.debug("Feedback submission failed", e);
    });
    enableRouteOverview();
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) FeedbackRequest(org.codice.ddf.catalog.ui.query.feedback.FeedbackRequest) Session(javax.mail.Session)

Example 54 with Session

use of javax.mail.Session in project Openfire by igniterealtime.

the class POP3AuthProvider method authenticate.

@Override
public void authenticate(String username, String password) throws UnauthorizedException {
    if (username == null || password == null) {
        throw new UnauthorizedException();
    }
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        }
    } else {
        // Unknown domain. Return authentication failed.
        throw new UnauthorizedException();
    }
    Log.debug("POP3AuthProvider.authenticate(" + username + ", ******)");
    // If cache is enabled, see if the auth is in cache.
    if (authCache != null && authCache.containsKey(username)) {
        String hash = authCache.get(username);
        if (StringUtils.hash(password).equals(hash)) {
            return;
        }
    }
    Properties mailProps = new Properties();
    mailProps.setProperty("mail.debug", String.valueOf(debugEnabled));
    Session session = Session.getInstance(mailProps, null);
    Store store;
    try {
        store = session.getStore(useSSL ? "pop3s" : "pop3");
    } catch (NoSuchProviderException e) {
        Log.error(e.getMessage(), e);
        throw new UnauthorizedException(e);
    }
    try {
        if (authRequiresDomain) {
            store.connect(host, port, username + "@" + domain, password);
        } else {
            store.connect(host, port, username, password);
        }
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
        throw new UnauthorizedException(e);
    }
    if (!store.isConnected()) {
        throw new UnauthorizedException("Could not authenticate user");
    }
    try {
        store.close();
    } catch (Exception e) {
    // Ignore.
    }
    // If cache is enabled, add the item to cache.
    if (authCache != null) {
        authCache.put(username, StringUtils.hash(password));
    }
    // See if the user exists in the database. If not, automatically create them.
    UserManager userManager = UserManager.getInstance();
    try {
        userManager.getUser(username);
    } catch (UserNotFoundException unfe) {
        String email = username + "@" + (domain != null ? domain : host);
        try {
            Log.debug("POP3AuthProvider: Automatically creating new user account for " + username);
            // Create user; use a random password for better safety in the future.
            // Note that we have to go to the user provider directly -- because the
            // provider is read-only, UserManager will usually deny access to createUser.
            UserManager.getUserProvider().createUser(username, StringUtils.randomString(8), null, email);
        } catch (UserAlreadyExistsException uaee) {
        // Ignore.
        }
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UserManager(org.jivesoftware.openfire.user.UserManager) Store(javax.mail.Store) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) Properties(java.util.Properties) NoSuchProviderException(javax.mail.NoSuchProviderException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session)

Example 55 with Session

use of javax.mail.Session in project translationstudio8 by heartsome.

the class MessageParser method main.

/**
	 * The main method.
	 * @param args
	 *            the arguments
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
public static void main(String[] args) throws IOException {
    Properties prep = new Properties();
    Session session = Session.getInstance(prep);
    try {
        Message msg = new MimeMessage(session, new FileInputStream("/data/terry/Desktop/email.eml"));
        MessageParser parser = new MessageParser(msg);
        System.out.println(parser.getPlainText());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
Also used : Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) FileNotFoundException(java.io.FileNotFoundException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) Session(javax.mail.Session)

Aggregations

Session (javax.mail.Session)110 MimeMessage (javax.mail.internet.MimeMessage)72 Properties (java.util.Properties)66 InternetAddress (javax.mail.internet.InternetAddress)49 MessagingException (javax.mail.MessagingException)47 Message (javax.mail.Message)31 Test (org.junit.Test)30 Transport (javax.mail.Transport)28 JMSession (com.zimbra.cs.util.JMSession)20 PasswordAuthentication (javax.mail.PasswordAuthentication)19 Date (java.util.Date)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 MimeMultipart (javax.mail.internet.MimeMultipart)16 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)15 IOException (java.io.IOException)15 SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)15 Authenticator (javax.mail.Authenticator)12 Multipart (javax.mail.Multipart)11 NoSuchProviderException (javax.mail.NoSuchProviderException)10 BodyPart (javax.mail.BodyPart)9