Showing posts with label smtp. Show all posts
Showing posts with label smtp. Show all posts

Friday, October 10, 2014

Using Java Send Email Using Smtp Server(Html, Attachment, Embedded Image)

First download java mail api jar from: https://java.net/projects/javamail/pages/Home or here.
And add this to your project classpath.


package com.pritom;

import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Created by pritom on 30/11/2016.
 */
public class SendEmailUsingSmtp {
    private static final String toAddress = "pritom@xxxxx.com";

    public static void main(String[] args) {
        google();
        //office();
        //bleep();
    }

    private static void google() {
        String host = "smtp.gmail.com";
        String port = "587";
        String userName = "xxxxx@gmail.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void office() {
        String host = "smtp.office365.com";
        String port = "587";
        String userName = "xxxxx@office.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void bleep() {
        String host = "bleep.xxxxx.com";
        String port = "587";
        String userName = "pritom@xxxxx.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void send(String host, String port, String userName, String password) {
        String attachments = "attachments/Attachment_1.gif;"
                + "attachments/Attachment_2.pdf;"
                + "attachments/Attachment_3.txt;"
                + "attachments/Attachment_4.docx;"
                + "attachments/Attachment_5.jpg";


        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("https.protocols", "TLSv1,SSLv3,SSLv2Hello");
        props.put("com.sun.net.ssl.enableECC", "false");
        props.put("jsse.enableSNIExtension", "false");

        String subject = "Java send mail example - TLS Authentication";

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        MimeMessage message = new MimeMessage(mailSession) {
            protected void updateMessageID() throws MessagingException {
                if (getHeader("Message-ID") == null)
                    super.updateMessageID();
            }
        };

        try {

            /* If failed to send email then fail report delivered to following email address */
            /* But remember not all smtp server allow use different email address */
            //props.put("mail.smtp.from", "pritomkucse@gmail.com");

            message.setFrom(new InternetAddress(userName, "Pritom Kumar", "UTF-8"));
            message.setReplyTo(InternetAddress.parse(userName, false));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress, "UTF-8"));

            message.setSentDate(new Date());
            message.setSubject(subject, "UTF-8");
            Multipart multipart = new MimeMultipart();

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("This is <b>message</b> body, pls see "
                    + "<i style='color: blue; font-size: 40px;'>attachments</i>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            for( int i = 0; i < attachments.split(";").length; i++) {
                String fileName = attachments.split(";")[i];
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(source.getName());
                messageBodyPart.setHeader("Content-ID", "<CONTENT_" + i + ">");
                multipart.addBodyPart(messageBodyPart);
            }

            /* Some custom headers added to email */
            message.addHeader("header-1", "header-1-value");
            message.addHeader("header-2", "header-2-value");

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("<h1>Attachments are added.</h1>Attached image as embedded:<br/>"
                    + "<img style='width: 50px;' src='cid:CONTENT_4'/>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart );
            println("Start sending email...");
            Transport.send(message);
            println("Mail sent with message ID=" + message.getMessageID());
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void println(Object o) {
        System.out.println(o);
    }
}

Console output would be like following

Start sending email...
Mail sent with message ID=<2059904228.1.1477967571904.JavaMail.pritom@PRITOM-PC>

In my gmail inbox email would be render as follows:



Use following code block if you want to use SSL Authentication


props.put("mail.smtp.host", HOST);
props.put("mail.smtp.socketFactory.port", PORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", PORT);

Wednesday, August 13, 2014

Python send plain/html email with attachment using smtp


import os
import tempfile
import mimetypes

from email.Utils import COMMASPACE, formatdate
from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEAudio import MIMEAudio
from email import Encoders


SMTPserver = 'smtp.mail.yahoo.com';
sender =     'some.name@yahoo.com';
destination = ['some.name@domain.com'];

USERNAME = "some.name@yahoo.com";
PASSWORD = "some.password";

contentHtml = """\
<b>Html message</b>
<div><span style='color: red'>Span with color red</span></div>
<div><span style='color: blue'>Span with color blue</span></div>
""";

contentPlain = 'Plain message';

contentAsPlainTextFile = 'Content as plain text file.';

subject = "Sent from Python";

conn = None;
try:
    msg = MIMEMultipart()
    msg['Subject'] = subject;
    msg['From'] = sender;
    msg['To'] = COMMASPACE.join(destination);
    msg['Date'] = formatdate(localtime=True);

    #Typical values for text_subtype are plain, html, xml
    msg.attach( MIMEText(contentHtml, 'html') );
    msg.attach( MIMEText(contentPlain, 'plain') );

    directory = os.path.dirname(os.path.realpath(__file__))
    files = [];
    files.append(os.path.join(directory, 'mail.simple.py'));
    files.append(os.path.join(directory, 'royal.jpg'));
    files.append(os.path.join(directory, 'audio.rm'));
    files.append(os.path.join(directory, 'xml7.xml'));

    tempdirectory = tempfile.mkdtemp()
    tempfilelocal = os.path.join(tempdirectory, 'Custom Text As Attachment.txt');
    tempfilelocal = open(tempfilelocal, 'w+b');
    tempfilelocal.write(contentAsPlainTextFile);
    tempfilelocal.seek(0);
    tempfilelocal.close();
    files.append(tempfilelocal.name);

    for fullpath in files:
        if not os.path.isfile(fullpath):
            continue;
        ctype, encoding = mimetypes.guess_type(fullpath);
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream';
        maintype, subtype = ctype.split('/', 1);
        if maintype == 'text':
            fp = open(fullpath);
            msgpart = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(fullpath, 'rb')
            msgpart = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(fullpath, 'rb')
            msgpart = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(fullpath, 'rb')
            msgpart = MIMEBase(maintype, subtype)
            msgpart.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msgpart)
        # Set the filename parameter
        msgpart.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fullpath))
        msg.attach(msgpart);

    conn = SMTP(SMTPserver);
    conn.set_debuglevel(False);
    conn.login(USERNAME, PASSWORD);
    conn.sendmail(sender, destination, msg.as_string());
    print("Mail sent.");
except Exception, exc:
    print( "Mail send failed: %s" % str(exc) );
finally:
    if conn is not None:
        conn.close()
        print("Connection closed.");

If server name and credentials are correct, you will receive email as below. In my case, it is my gmail inbox.


Sunday, July 21, 2013

Sending E-mails in php using yahoo smtp

<?php 
require 'Mail/class.phpmailer.php';

$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP  
$mail->Host 'plus.smtp.mail.yahoo.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication  
$mail->Username   'yourname@yahoo.com'// SMTP username  
$mail->Password   'xxxxxxxxxxxxxxxxxxxxx'// SMTP password  
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...  
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout  
$mail->From       'yourname@yahoo.com'; 
$mail->FromName   'Pritom Kumar Mondal'; 
// Add a recipient 
$mail->AddAddress('yourname@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('yourname@yahoo.com''Pritom YAHOO'); 
$mail->AddReplyTo('yourname@gmail.com''Reply To');

$mail->AddCC('yourname@gmail.com');
$mail->AddBCC('yourname@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters

// Add attachments 
 

$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 
$mail->IsHTML(true); // Set email format to HTML  
$mail->Subject 'E-mail sent using yahoo smtp'; 

$mail->Body    'This is the HTML message body <b>in bold!</b>, sent using yahoo smtp';

$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}
echo 
'Message has been sent';?>