public void enviarEmail() { FacesContext context = FacesContext.getCurrentInstance(); AutenticaUsuario autenticaUsuario = new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL); Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario); session.setDebug(true); try { Transport envio = null; MimeMessage email = new MimeMessage(session); email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para)); email.setFrom(new InternetAddress(this.de)); email.setSubject(this.assunto); email.setContent(this.mensagem, "text/plain"); email.setSentDate(new Date()); envio = session.getTransport("smtp"); envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL); email.saveChanges(); envio.sendMessage(email, email.getAllRecipients()); envio.close(); context.addMessage(null, new FacesMessage("E-mail enviado com sucesso")); } catch (AddressException e) { FacesMessage msg = new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage()); context.addMessage(null, msg); return; } catch (MessagingException e) { FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage()); context.addMessage(null, msg); return; } }
public static void sendSmtpMessage(Session session, Message message, Address[] recipients) throws MessagingException { // message = cloneMimeMessage(message); message.setSentDate(new Date()); setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER); message.saveChanges(); LOG.info( "Sending message '" + message.getSubject() + "' from '" + Str.format(message.getFrom()) + "' to '" + Str.format(recipients) + "'."); Transport trans = session.getTransport("smtp"); Properties properties = session.getProperties(); trans.connect( properties.getProperty("mail.smtp.host"), properties.getProperty("mail.smtp.auth.user"), properties.getProperty("mail.smtp.auth.password")); trans.sendMessage(message, recipients); trans.close(); }
public void mail(String toAddress, String subject, String body) { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.ssl.enable", true); Authenticator authenticator = null; if (login) { props.put("mail.smtp.auth", true); authenticator = new Authenticator() { private PasswordAuthentication pa = new PasswordAuthentication(username, password); @Override public PasswordAuthentication getPasswordAuthentication() { return pa; } }; } Session s = Session.getInstance(props, authenticator); s.setDebug(debug); MimeMessage email = new MimeMessage(s); try { email.setFrom(new InternetAddress(from)); email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); email.setSubject(subject); email.setSentDate(new Date()); email.setText(body); Transport.send(email); } catch (MessagingException ex) { ex.printStackTrace(); } }
public static Session createSmtpSession( String host, Integer port, boolean tls, String user, String password) { if (Str.isBlank(host)) throw new IllegalArgumentException("host ist blank"); if (Str.isBlank(user)) user = null; if (Str.isBlank(password)) password = null; Properties p = new Properties(); p.setProperty("mail.mime.charset", charset); p.setProperty("mail.transport.protocol", "smtp"); p.setProperty("mail.smtp.host", host); if (port != null) p.put("mail.smtp.port", port); p.put("mail.smtp.starttls.enable", String.valueOf(tls)); boolean auth = user != null && password != null; p.setProperty("mail.smtp.auth", String.valueOf(auth)); if (user != null) p.setProperty("mail.smtp.auth.user", user); if (password != null) p.setProperty("mail.smtp.auth.password", password); Session session = Session.getInstance(p); if (auth) { session.setPasswordAuthentication( new URLName("local"), new PasswordAuthentication(user, password)); } return session; }
// send emails public void sendEmail(String to, String mess) { try { String host = "smtp.gmail.com"; String username = "******"; String password = "******"; String email = "*****@*****.**"; Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.user", username); props.put("mail.smtp.password", password); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session s = Session.getDefaultInstance(props, null); MimeMessage m = new MimeMessage(s); m.setFrom(new InternetAddress(email)); m.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); m.setSubject("Secret Santa"); m.setText(mess); Transport t = s.getTransport("smtp"); t.connect(host, 465, username, password); t.sendMessage(m, m.getRecipients(Message.RecipientType.TO)); t.close(); } catch (Exception ex) { ex.printStackTrace(); } }
public void test() throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", SMTP_HOST_NAME); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(username.getText())); message.setSubject(subject.getText()); String s = msgfield.getText(); message.setContent(s, "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText())); System.out.println("8i m here "); try { transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "invalid username or password"); } System.out.println("8i m here also yaar"); // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO)); transport.sendMessage(message123, message123.getAllRecipients()); transport.close(); System.out.println(s); }
public void send(String mailto, String subject, String textMessage, String contentType) throws FileNotFoundException, MessagingException { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.put("mail.smtp.user", smtpUsername); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.ssl", "true"); Authenticator auth = new SMTPAuthenticator(); Session smtpSession = Session.getInstance(props, auth); smtpSession.setDebug(true); Message message = new MimeMessage(smtpSession); InternetAddress[] address = {new InternetAddress(mailto)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(textMessage, contentType); Transport tr = smtpSession.getTransport("smtp"); tr.connect(smtpHost, smtpUsername, smtpPassword); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
public boolean send() { try { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.debug", "true"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props, new GJMailAuthenticator()); session.setDebug(true); Transport transport = session.getTransport(); InternetAddress addressFrom = new InternetAddress("*****@*****.**"); MimeMessage message = new MimeMessage(session); message.setSender(addressFrom); message.setSubject(subject); message.setContent(text, "text/html"); InternetAddress addressTo = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, addressTo); transport.connect(); Transport.send(message); transport.close(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public void envioCorreo(String mensaje, String modo) { String subject = ""; String destination = obtenerParametros("destinatario"); String mailHost = obtenerParametros("mailHost"); String source = obtenerParametros("origen"); if (modo.equals("Fallo")) subject = "Aplicaci\363n de Carga y Validaci\363n de datos. ERROR!!"; else subject = "Aplicacion de Carga y Validaci\363n de datos. MENSAJE INFORMATIVO"; Properties properties = new Properties(); properties.put("mail.smtp.host", mailHost); properties.put("mail.from", source); Session session = Session.getInstance(properties, null); try { Message message = new MimeMessage(session); InternetAddress address[] = {new InternetAddress(destination)}; message.setRecipients(javax.mail.Message.RecipientType.TO, address); message.setFrom(new InternetAddress(source)); message.setSubject(subject); message.setContent(mensaje + "\n", "text/plain"); Transport transport = session.getTransport(address[0]); transport.connect(); transport.sendMessage(message, address); } catch (Exception e1) { e1.printStackTrace(); } }
public static void main(String[] args) throws MessagingException, IOException { IMAPFolder folder = null; Store store = null; String subject = null; Flag flag = null; try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.host", "imap.googlemail.com"); SimpleAuthenticator authenticator = new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy"); Session session = Session.getDefaultInstance(props, null); // Session session = Session.getDefaultInstance(props, authenticator); store = session.getStore("imaps"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); store.connect("*****@*****.**", "hhy8611hhy"); // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email // account folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account if (!folder.isOpen()) folder.open(Folder.READ_WRITE); Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages(); System.out.println("No of get Messages : " + messages.length); System.out.println("No of Messages : " + folder.getMessageCount()); System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount()); System.out.println("No of New Messages : " + folder.getNewMessageCount()); System.out.println(messages.length); for (int i = 0; i < messages.length; i++) { System.out.println( "*****************************************************************************"); System.out.println("MESSAGE " + (i + 1) + ":"); Message msg = messages[i]; // System.out.println(msg.getMessageNumber()); // Object String; // System.out.println(folder.getUID(msg) subject = msg.getSubject(); System.out.println("Subject: " + subject); System.out.println("From: " + msg.getFrom()[0]); System.out.println("To: " + msg.getAllRecipients()[0]); System.out.println("Date: " + msg.getReceivedDate()); System.out.println("Size: " + msg.getSize()); System.out.println(msg.getFlags()); System.out.println("Body: \n" + msg.getContent()); System.out.println(msg.getContentType()); } } finally { if (folder != null && folder.isOpen()) { folder.close(true); } if (store != null) { store.close(); } } }
public static void sendEmail(String title, String message, String email) throws MessagingException { Properties props = new Properties(); props.setProperty("mail.smtp.auth", "true"); // 设置访问smtp服务器需要认证 props.setProperty("mail.transport.protocol", "smtp"); // 设置访问服务器的协议 Session session = Session.getDefaultInstance(props); session.setDebug(true); // 打开debug功能 Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(user)); // 设置发件人,163邮箱要求发件人与登录用户必须一致(必填),其它邮箱不了解 msg.setText(message); // 设置邮件内容 msg.setSubject("Test"); // 设置邮件主题 Transport trans = session.getTransport(); try { trans.connect("smtp.163.com", 25, user, pwd); // 连接邮箱smtp服务器,25为默认端口 } catch (Exception e) { e.printStackTrace(); } try { trans.sendMessage(msg, new Address[] {new InternetAddress(email)}); // 发送邮件 } catch (Exception e) { e.printStackTrace(); } trans.close(); // 关闭连接 }
@Override public void sendEmail(String id, String total, String email) { Properties prop = new Properties(); prop.setProperty("mail.transport.protocol", "smtp"); Message message = null; Transport transport = null; Session session = null; try { session = Session.getDefaultInstance(prop); session.setDebug(true); // 创建一封新有邮件 message = (Message) new MimeMessage(session); // 标题、正文内容、发件人地址 message.setSubject("订单支付成功邮件(系统邮件)"); message.setContent("订单编号为:" + id + ",金额 为: " + total + ",已经支付成功!", "text/html;charset=utf-8"); message.setFrom(new InternetAddress("*****@*****.**")); // 设置用户名密码,收件人地址,发送邮件 transport = session.getTransport(); // 通过用户名与密码, 链接邮件服务器 transport.connect("smtp.sina.com", "soft03_test", "soft03_test"); transport.sendMessage(message, new Address[] {new InternetAddress(email)}); } catch (Exception e) { throw new RuntimeException(e); } finally { try { // 关闭客户端(释放资源) transport.close(); } catch (Exception e) { throw new RuntimeException(e); } } }
/** добавить сообщение в папку "отправленные" */ private void appendEmailToSent(Message message) { try { Properties properties = new Properties(); properties.put("mail.store.protocol", "imaps"); MailSSLSocketFactory socketFactory = new MailSSLSocketFactory(); socketFactory.setTrustAllHosts(true); properties.put("mail.imaps.ssl.socketFactory", socketFactory); properties.put("mail.imaps.ssl.trust", "*"); properties.put("mail.imaps.ssl.checkserveridentity", "false"); properties.put("mail.imaps.host", HOST); properties.put("mail.imaps.port", IMAP_PORT); // присоединиться к IMAP Session session = Session.getDefaultInstance(properties, null); Store store = session.getStore("imaps"); store.connect(HOST, IMAP_PORT, POST_LOGIN, POST_PASSWORD); // добавить сообщение в папку Folder inbox = store.getFolder("Sent"); inbox.open(Folder.READ_WRITE); Message[] msgs = {message}; inbox.appendMessages(msgs); inbox.close(false); store.close(); } catch (Exception e) { getActionResult().addMessage("не удалось поместить письмо в папку отправленные"); } }
public static void sendSmtpMessageNoAuth( String smtpHost, String smtpPort, String from, String to, String subject, String content, List<String> filenames, boolean debug) { logger.info("Send mail to {}, content: {}.", to, content); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.host", smtpHost); props.put("mail.smtp.auth", "false"); props.put("mail.smtp.port", smtpPort); props.put("mail.debug", debug ? "true" : "false"); Session session = Session.getDefaultInstance(props); session.setDebug(debug); sendMimeMessage(from, to, subject, content, filenames, session); logger.info("Mail sent"); }
public static void sendSmtpSslMessage( String smtpHost, String smtpSslPort, String username, String password, String from, String to, String subject, String content, List<String> filenames, boolean debug) { logger.info("Send mail to {}, content: {}.", to, content); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", smtpSslPort); props.put("mail.smtp.socketFactory.port", smtpSslPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.debug", debug ? "true" : "false"); Session session = Session.getDefaultInstance(props, new UsrPwdAuthenticator(username, password)); session.setDebug(debug); sendMimeMessage(from, to, subject, content, filenames, session); logger.info("Mail sent"); }
public static void sendEmail( InternetAddress from, InternetAddress to, String content, String requester) throws MessagingException, UnsupportedEncodingException { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", SMTP_HOST_NAME); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject("MN Traffic Generation is used by " + requester); message.setContent(content, "text/plain"); message.addRecipient(Message.RecipientType.TO, to); InternetAddress[] replyto = new InternetAddress[1]; replyto[0] = from; message.setFrom(from); message.setReplyTo(replyto); message.setSender(from); transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
@Override public void run() { LOGGER.info("***********Inside send e-Mail Thread************"); LOGGER.info("Sending email to:: E-mail Address::" + emailModel.getToaddess()); Session mailSession = createSmtpSession(); mailSession.setDebug(true); List<String> toAddresses = new ArrayList<String>(); try { Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailModel.getSubject()); message.setFrom(new InternetAddress(emailModel.getFromAddress())); message.setContent(emailModel.getContent(), "text/html"); toAddresses.add(emailModel.getToaddess()); transport.connect(); Iterator<String> itr = toAddresses.iterator(); while (itr.hasNext()) { String toAddress = (String) itr.next(); message.addRecipients(Message.RecipientType.TO, toAddress); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); } LOGGER.info("Successfully sent email to:: E-mail Address::" + emailModel.getToaddess()); } catch (MessagingException e) { LOGGER.error("Cannot Send email", e); } }
public void postMail(String recipients[], String subject, String message, String from) throws MessagingException { boolean debug = false; // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.timeout", 60000); Authenticator auth = new SMTPAuthenticator(); Session session = Session.getDefaultInstance(props, auth); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/html"); Transport.send(msg); }
public boolean connectToMailBox() { try { Properties props = new Properties(); props.setProperty("mail.imap.ssl.enable", "true"); // required for Gmail props.setProperty("mail.imap.auth.mechanisms", "XOAUTH2"); props.setProperty("mail.store.protocol", config.getString("imap.protocol")); props.setProperty("mail.imaps.fetchsize", "" + fetchSize); props.setProperty("mail.imaps.timeout", "" + rTimeout); props.setProperty("mail.imaps.writetimeout", "" + rTimeout); props.setProperty("mail.imaps.connectiontimeout", "" + cTimeout); props.setProperty("mail.imaps.connectionpooltimeout", "" + cTimeout); Session session = Session.getInstance(props); mailbox = session.getStore(config.getString("imap.protocol")); mailbox.connect( config.getString("imap.host"), config.getString("imap.user"), config.getString("imap.access_token")); LOG.info("Connected to mailbox"); return true; } catch (MessagingException e) { LOG.error("Connection failed", e); return false; } }
public static void SendMail(String to, String subject, String Content) { try { // setup the mail server properties Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // set up the message Session session = Session.getInstance(props); Message message = new MimeMessage(session); // add a TO address message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // add a multiple CC addresses // message.setRecipients(Message.RecipientType.CC, // InternetAddress.parse("[email protected],[email protected]")); message.setSubject(subject); message.setContent(Content, "text/plain"); Transport transport = session.getTransport("smtp"); transport.connect("smtp.gmail.com", 587, "aaa", "pass"); transport.sendMessage(message, message.getAllRecipients()); // System.out.println("Send email via gmail..."); } catch (Exception e) { System.out.println(e.getMessage()); } }
public void SendEmail(String email, String contestToken) { String to = email; String from = "Tyumen_ACM_Society"; String host = "smtp.gmail.com"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); props.put("mail.stmp.user", "*****@*****.**"); props.put("mail.smtp.password", "475508th"); 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.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props, new SmtpAuthenticator()); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Registration on acm.utmn.ru"); message.setText( "Hello! Thank you for registration on acm.utmn.ru! Use next token to submit tasks: " + contestToken); Transport t = session.getTransport("smtp"); t.send(message); System.out.println("Message was successfully sent."); } catch (MessagingException mex) { mex.printStackTrace(); } }
/** * Initialize this plugin. This method only called when the plugin is instantiated. * * @param servletConfig Servlet config object for the plugin to retrieve any initialization * parameters * @param blojsomConfiguration {@link org.blojsom.blog.BlojsomConfiguration} information * @throws BlojsomPluginException If there is an error initializing the plugin */ public void init(ServletConfig servletConfig, BlojsomConfiguration blojsomConfiguration) throws BlojsomPluginException { String hostname = servletConfig.getInitParameter(SMTPSERVER_IP); if (hostname != null) { if (hostname.startsWith("java:comp/env")) { try { Context context = new InitialContext(); _mailsession = (Session) context.lookup(hostname); } catch (NamingException e) { _logger.error(e); throw new BlojsomPluginException(e); } } else { String username = servletConfig.getInitParameter(SMTPSERVER_USERNAME_IP); String password = servletConfig.getInitParameter(SMTPSERVER_PASSWORD_IP); Properties props = new Properties(); props.put(SESSION_NAME, hostname); if (BlojsomUtils.checkNullOrBlank(username) || BlojsomUtils.checkNullOrBlank(password)) { _mailsession = Session.getInstance(props, null); } else { _mailsession = Session.getInstance(props, new SimpleAuthenticator(username, password)); } } } }
/** * main de prueba * * @param args Se ignoran. */ public static void main(String[] args) { try { // Propiedades de la conexión Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.disable", "true"); props.setProperty("mail.smtp.auth.plain.disable", "true"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.user", "*****@*****.**"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); session.setDebug(true); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("*****@*****.**")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**")); message.setSubject("Hola"); message.setText("Mensajito con Java Mail" + "de los buenos." + "poque si"); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("*****@*****.**", "admmphinv2012"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void send(MimeMessage message) throws MailerException { Session session = Session.getDefaultInstance(getConfiguration()); if (this.from != null) { try { message.setFrom(from); } catch (MessagingException e) { throw new MailerException(e); } } try { Transport tr = session.getTransport("smtp"); if (getConfigurationProperty(Configuration.SMTP.AUTH, "true").equalsIgnoreCase("true")) { tr.connect( getConfigurationProperty(Configuration.SMTP.USER), getConfigurationProperty(Configuration.SMTP.PASSWORD)); } else { tr.connect(); } tr.sendMessage(message, message.getAllRecipients()); tr.close(); } catch (MessagingException e) { throw new MailerException(e); } }
public static void send( String nomContact, Integer numFacture, Double montantCommande, Integer nbLots, String typeEnvoi, String adresseContact) throws Exception { Properties props = System.getProperties(); props.put("mail.smtps.host", "smtp.orange.fr"); props.put("mail.smtps.auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("*****@*****.**")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adresseContact, false)); String corpsMessage = "Bonjour " + nomContact + "\n\n" + "votre commande n°" + numFacture + " d'un montant de " + montantCommande + "€ TTC vient d'être traitée.\n\n" + typeEnvoi + " \n\n" + "L'équipe du ciné cap vert vous remercie de votre confiance.\n\n\n\n" + " P.S.: Retrouvez en pièce jointe le mode d'emploi des chèques cinéma sur notre interface de réservation en ligne"; msg.setSubject("Votre commande de " + nbLots + " lots de chèques cinéma vient d'être traitée."); msg.setHeader("X-Mailer", "Test En-tete"); msg.setSentDate(new Date()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(corpsMessage); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.attachFile("ccvad.png"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); SMTPTransport t = (SMTPTransport) session.getTransport("smtps"); t.connect("smtp.orange.fr", "*****@*****.**", "popcorn21800"); t.sendMessage(msg, msg.getAllRecipients()); System.out.println("Réponse: " + t.getLastServerResponse()); t.close(); }
public static int removeEmails(Account account, String protocol) throws MessagingException, UnknownHostException { int count = 0; Session session = Session.getInstance( Protocol.POP3.equals(protocol) ? getPop3MailProperties(account) : getImapMailProperties(account)); Folder inbox; // store = session.getStore("imap"); if (account.getLoginName().contains("@yahoo.")) { IMAPStore imapstore = (IMAPStore) session.getStore(protocol); yahooConnect(account, imapstore, true); inbox = imapstore.getFolder("INBOX"); } else { Store store = session.getStore(protocol); store.connect(account.getReceiveHost(), account.getLoginName(), account.getPassword()); inbox = store.getFolder("INBOX"); } inbox.open(Folder.READ_WRITE); count = inbox.getMessageCount(); for (Message message : inbox.getMessages()) { message.setFlag(Flags.Flag.DELETED, true); } inbox.close(true); return count; }
@Test public void testGetFolder() throws MessagingException { Properties props; Session session; Folder folder; props = new Properties(); props.put("mail.host", "pop.gmail.com"); props.put("mail.store.protocol", "pop3s"); props.put("mail.pop3s.auth", "true"); props.put("mail.pop3s.port", 995); session = Session.getInstance(props, null); Store instance; // with wrong param instance = session.getStore(); instance.connect("*****@*****.**", "spamreturn"); try { folder = instance.getFolder(""); } catch (MessagingException ex) { assertTrue(true); } // with valid param try { folder = instance.getFolder("INBOX"); assertTrue(true); } catch (MessagingException ex) { fail("Should not throw MessagingException"); } }
/** 发�?邮件 */ public boolean sendOut() { try { mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发�?邮件...."); Session mailSession = Session.getInstance(props, null); Transport transport = mailSession.getTransport("smtp"); transport.connect((String) props.get("mail.smtp.host"), username, password); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); // 如果抄�?人为null 不添加抄送人 if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC)); // transport.send(mimeMsg); System.out.println("发送邮件成功"); transport.close(); return true; } catch (Exception e) { System.err.println("邮件发送失败" + e); e.printStackTrace(); return false; } }
public static void main(String[] args) throws Exception { String pop3Server = "pop.163.com"; String protocol = "pop3"; String user = "******"; String pwd = "kissyou770"; Properties properties = new Properties(); properties.setProperty("mail.store.protocol", protocol); properties.setProperty("mail.pop3.host", pop3Server); Session session = Session.getInstance(properties); session.setDebug(true); Store store = session.getStore(); store.connect(pop3Server, user, pwd); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); int mailCounts = messages.length; // for (Message message : messages) { Message message = messages[mailCounts - 1]; new MyMail().mailReceiver(message); folder.close(false); store.close(); }