E-mail

8 respostas
F

Oi pessoal,

Vcs sabem como mandar e-mails atraves de um programa em java??? :idea:

8 Respostas

M

…fazendo uso da API JavaMail do J2EE :slight_smile: , em casa eu tenho um helloworld disso em JSP…, só tenho q vasculhar hehehe

D

voce tambem pode fazer isso via Sockets :idea:

ai voce nao precisa instalar outra API… :wink:

se voce quizer tenho um codigo de exemplo disso

D

no site do guj (guj.com.br), na área de artigos, tem um tutorial sobre como enviar emails usando a API JavaMail

F

“denis_arruda”:
voce tambem pode fazer isso via Sockets :idea:

ai voce nao precisa instalar outra API… :wink:

se voce quizer tenho um codigo de exemplo disso

Sim.quero dar uma olhada no seu código. Vc pode disponibiliza-lo para mim?

F

Obrigado!! :lol:

M

ta ai, tirei do jspbrasil, página jsp onde tu coloca os dados pro e-mail:

<html>
<body>

<form action="enviaremail.jsp" method"post">
<table border="0" align="center" bgcolor="tan">
<tr>
<td><b>Para..:</b></td>
<td><input type="Text" name="para"</td>
</tr>
<tr>
<td><b>De..:</b></td>
<td><input type="Text" name="de"</td>
</tr>
<tr>
<td><b>Assunnto..:</b></td>
<td><input type="Text" name="assunto"</td>
</tr>
<tr>
<td colspan="2">
<textarea name="mensagem" rows=10 cols=45></textarea>
</td>
</tr>
</table>
<center> <input type="Submit" value="Enviar Email"></center>
</form>

</body>
</html>

..ai segue o código da página jsp (enviaremail.jsp) com a lógica de programação responsável por criar e enviar o mail:

<html>
<body>
<%@ page import="jspbrasil.Email" %>
<jsp:useBean id="email" scope="session" class="jspbrasil.Email"/>
<%
 try {
 
   String mailServer = "mail.seumailserver.com.br"
   String assunto = request.getParameter("assunto")
   String para = { request.getParameter("para") };
   String de = request.getParameter("de");
   String mensagem =request.getParameter("mensagem");
   email.sendSimpleMail(mailServer, assunto, para, de, mensagem);
%>
<p>Email enviado com Sucesso !!!</p>
<%
  }
  catch (AdressException e) { %>
    <p>Endereço de Email inválido</p>	
<%}%>
<%
  catch (MessagingException e) { %>
    <p>Impossível enviar o email.</p>	
<%}%>

</body>
</html>

agora a classe responsável por enviar o mail:

package  jspbrasil;

import javax.mail.*;
import javax.mail.internet.*;
import.java.util.*;

public class Email {

   public void sendSimpleMail (String mailServer, String subject,
      String to,String from, String mensagem )
   throws AddressException, MessageException 
   {

      Properties mailProps = new Properties();
      //definição do mailserver

      mailProps.put("mail.smtp.host", mailServer)

      Session mailSession = Session.getDefaultInstance(mailProps, null);

      //As duas linhas seguintes de código, colocam no
      //formato de endereços, 
      //supostamente válidos, de email os dados 
      //passados pelos parâmetros to e from.
      InternetAdress destinatario = new InternetAdress (to);
      InternetAdress remetente = new InternetAdress (from);

      //As duas linhas de código a seguir, são 
      //responsáveis por setar os atributos e 
      //propriedas necessárias do objeto message 
      //para que o email seja enviado.
      //inicialização do objeto Message 
      Message message = new MimeMessage (mailSession);

      //Definição de quem está enviando o email
      message.setFrom(remetente);

      //define o(s) destinatário(s) e qual o tipo do 
      //destinatário.
      //os possíveis tipos de destinatário: TO, CC, BCC
	
      message.setRecipient( Message.RecipientType.TO, destinatário );
      //definição do assunto do email
		
      message.setSubject (subject);
      //definição do conteúdo da mesnagem e do 
      //tipo da mensagem
	
      message.setContent (mensagem.toString(), "text/plain");
      //a linha de código seguinte é a responsável 
      //pelo envio do email

      Transport.send (message);
   }

}
D

aqui está:

/**
 * @version 1.00 1999-08-27
 * @author Cay Horstmann
 */

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class MailTest
{  public static void main(String[] args)
   {  JFrame frame = new MailTestFrame();
      frame.show();
   }
}

class MailTestFrame extends JFrame
   implements ActionListener
{  public MailTestFrame()
   {  setTitle("MailTest");
      setSize(300, 300);
      addWindowListener(new WindowAdapter()
         {  public void windowClosing(WindowEvent e)
            {  System.exit(0);
            }
         } );

      getContentPane().setLayout(new GridBagLayout());

      GridBagConstraints gbc = new GridBagConstraints();
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.weightx = 0;
      gbc.weighty = 0;

      gbc.weightx = 0;
      add(new JLabel("From:"), gbc, 0, 0, 1, 1);
      gbc.weightx = 100;
      from = new JTextField(20);
      add(from, gbc, 1, 0, 1, 1);

      gbc.weightx = 0;
      add(new JLabel("To:"), gbc, 0, 1, 1, 1);
      gbc.weightx = 100;
      to = new JTextField(20);
      add(to, gbc, 1, 1, 1, 1);

      gbc.weightx = 0;
      add(new JLabel("SMTP server:"), gbc, 0, 2, 1, 1);
      gbc.weightx = 100;
      smtpServer = new JTextField(20);
      add(smtpServer, gbc, 1, 2, 1, 1);

      gbc.fill = GridBagConstraints.BOTH;
      gbc.weighty = 100;
      message = new JTextArea();
      add(new JScrollPane(message), gbc, 0, 3, 2, 1);

      response = new JTextArea();
      add(new JScrollPane(response), gbc, 0, 4, 2, 1);

      gbc.weighty = 0;
      JButton sendButton = new JButton("Send");
      sendButton.addActionListener(this);
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(sendButton);
      add(buttonPanel, gbc, 0, 5, 2, 1);
   }

   private void add(Component c, GridBagConstraints gbc,
      int x, int y, int w, int h)
   {  gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = w;
      gbc.gridheight = h;
      getContentPane().add(c, gbc);
   }

   public void actionPerformed(ActionEvent evt)
   {  SwingUtilities.invokeLater(new Runnable()
        {  public void run()
           {   sendMail();
           }
        });
   }

   public void sendMail()
   {  try
      {  Socket s = new Socket(smtpServer.getText(), 25);

         out = new PrintWriter(s.getOutputStream());
         in = new BufferedReader(new
            InputStreamReader(s.getInputStream()));

         String hostName
            = InetAddress.getLocalHost().getHostName();

         send(null);
         send("HELO " + hostName);
         send("MAIL FROM: " + from.getText());
         send("RCPT TO: " + to.getText());
         send("DATA");
         out.println(message.getText()+"\r");
         send(".");
         s.close();
      }
      catch (IOException exception)
      {  response.append("Error: " + exception);
      }
   }

   public void send(String s) throws IOException
   {  if (s != null)
      {  response.append(s + "\n");
         out.println(s+"\r");
         out.flush();
      }
      String line;
      if ((line = in.readLine()) != null)
         response.append(line + "\n");
   }

   private BufferedReader in;
   private PrintWriter out;
   private JTextField from;
   private JTextField to;
   private JTextField smtpServer;
   private JTextArea message;
   private JTextArea response;
}
F

Obrigado Denis e Matheus pela ajuda!!

Criado 12 de junho de 2004
Ultima resposta 13 de jun. de 2004
Respostas 8
Participantes 4