Posts Tagged ‘Email client’

email

 

That is for sending Email using “mail.smtp.auth”

public static String sendEmail(final String username, final String password, String replyto, String port, String host, String from, String to, String messagesubject, String messageboday, String attactmentpath) {

//   final String username = “zakhter@truemeridian.com”;
//  final String password = “password”;

Properties props = new Properties();
props.put(“mail.smtp.auth”, “true”);
//props.put(“mail.smtp.starttls.enable”, “true”);
props.put(“mail.smtp.host”, host);//”smtp.truemeridian.com”);
props.put(“mail.smtp.port”, port);
props.setProperty(“mail.smtp.ssl.trust”, host);

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

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));//”zakhter@truemeridian.com”));
message.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(to));//”zeeshanakhter2009@gmail.com”));

InternetAddress replyAddresses[] = new InternetAddress[1];
replyAddresses[0] = new InternetAddress(replyto);
message.setReplyTo(replyAddresses);
message.setSubject(messagesubject);
message.setText(messageboday);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageboday);

// Create a multipar message
Multipart multipart = new MimeMultipart();

// Set text message part
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(attactmentpath);
messageBodyPart.setDataHandler(new DataHandler(source));
attactmentpath = attactmentpath.replace(“\\”, “/”);
String[] fileName = attactmentpath.split(“/”);
System.out.println(“\n\nPath3=” + attactmentpath);
// for(int i=0;i
// {
//    attactmentpath=fileName[i];
// }
attactmentpath = fileName[fileName.length – 1];
messageBodyPart.setFileName(attactmentpath);
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts
message.setContent(multipart);
message.setContent(multipart);

Transport.send(message);

System.out.println(“Done”);

return “Sent”;
} catch (Exception e) {
e.printStackTrace();
return “Fail”;
}
}

 

Advertisements

English: SMTP transfer model Blue arrows can b...

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

public class MailClient
{
public static void main(String []args)
{
JFrame frame = new MailClientFrame();
frame.show();
}
}
class MailClientFrame extends JFrame implements ActionListener
{

private BufferedReader in;
private PrintWriter out;
private JTextField from;
private JTextField to;
private JTextField smtpServer;
private JTextArea message;
private JTextArea response;
private JLabel fromLbl;
private JLabel toLbl;
private JLabel serverLbl;

public MailClientFrame()
{
setTitle(“Mail Client”);
setSize(250,400);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);

getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

fromLbl = new JLabel(“From: “);
getContentPane().add(fromLbl);

from = new JTextField(20);
getContentPane().add(from);

toLbl = new JLabel(“To: “);
getContentPane().add(toLbl);

to = new JTextField(20);
getContentPane().add(to);

serverLbl = new JLabel(“SMTP Server:”);
getContentPane().add(serverLbl);

smtpServer = new JTextField(20);
getContentPane().add(smtpServer);

message = new JTextArea(5,20);
getContentPane().add(message);

JScrollPane p = new JScrollPane(message);
getContentPane().add(p);

response = new JTextArea(5,20);
getContentPane().add(response);

JScrollPane p1 = new JScrollPane(response);
getContentPane().add(p1);

JButton sendButton  = new JButton(“Send”);
sendButton.addActionListener(this);

JPanel buttonPanel = new JPanel();
buttonPanel.add(sendButton);

getContentPane().add(sendButton);

}

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());
send(“.”);
s.close();
}
catch(IOException e)
{
response.append(“Error:” + e);
}
}

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

Image representing Gmail as depicted in CrunchBase





This is what I do when i want to send email with attachment, work fine. :)


public class NewClass {

    public static void main(String[] args) {
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); // smtp port
            Authenticator auth = new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username-gmail", "password-gmail");
                }
            };
            Session session = Session.getDefaultInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("username-gmail@gmail.com"));
            msg.setSubject("Try attachment gmail");
            msg.setRecipient(RecipientType.TO, new InternetAddress("username-gmail@gmail.com"));
            //add atleast simple body
            MimeBodyPart body = new MimeBodyPart();
            body.setText("Try attachment");
            //do attachment
            MimeBodyPart attachMent = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
            attachMent.setDataHandler(new DataHandler(dataSource));
            attachMent.setFileName("file-sent.txt");
            attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(body);
            multipart.addBodyPart(attachMent);
            msg.setContent(multipart);
            Transport.send(msg);
        } catch (AddressException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}