多語言實現電子郵件發送功能

C

#include <curl/curl.h>
#include <string.h>
#include <stdio.h>
 
#define from    "<[email protected]>"
#define to      "<[email protected]>"
#define cc      "<[email protected]>"
 
static const char *payload_text[] = {
  "Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n",
  "To: " to "\r\n",
  "From: " from " (Example User)\r\n",
  "Cc: " cc " (Another example User)\r\n",
  "Message-ID: <ecd7db36-10ab-437a-9g3a-e652b9458efd@"
  "rfcpedant.example.org>\r\n",
  "Subject: Sanding mail via C\r\n",
  "\r\n",
  "This mail is being sent by a C program.\r\n",
  "\r\n",
  "It connects to the GMail SMTP server, by far, the most popular mail program of all.\r\n",
  "Which is also probably written in C.\r\n",
  "To C or not to C..............\r\n",
  "That is the question.\r\n",
  NULL
};
 
struct upload_status {
  int lines_read;
};
 
static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
  struct upload_status *upload_ctx = (struct upload_status *)userp;
  const char *data;
 
  if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
    return 0;
  }
 
  data = payload_text[upload_ctx->lines_read];
 
  if(data) {
    size_t len = strlen(data);
    memcpy(ptr, data, len);
    upload_ctx->lines_read++;
 
    return len;
  }
 
  return 0;
}
 
int main(void)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  struct curl_slist *recipients = NULL;
  struct upload_status upload_ctx;
 
  upload_ctx.lines_read = 0;
 
  curl = curl_easy_init();
  if(curl) {
 
    curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");
 
    curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:465");
 
    curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
 
    curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");
 
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
 
    recipients = curl_slist_append(recipients, to);
    recipients = curl_slist_append(recipients, cc);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
 
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
    curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
 
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
 
    res = curl_easy_perform(curl);
 
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
 
    curl_slist_free_all(recipients);
 
    curl_easy_cleanup(curl);
  }
 
  return (int)res;
}

C++

// on Ubuntu: sudo apt-get install libpoco-dev
// or see http://pocoproject.org/
// compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation
 
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
 
using namespace Poco::Net;
 
int main (int argc, char **argv)
{
  try
    {
      MailMessage msg;
 
      msg.addRecipient (MailRecipient (MailRecipient::PRIMARY_RECIPIENT,
                                       "[email protected]",
                                       "Alice Moralis"));
      msg.addRecipient (MailRecipient (MailRecipient::CC_RECIPIENT,
                                       "[email protected]",
                                       "Patrick Kilpatrick"));
      msg.addRecipient (MailRecipient (MailRecipient::BCC_RECIPIENT,
                                       "[email protected]",
                                       "Michael Carmichael"));
 
      msg.setSender ("Roy Kilroy <[email protected]>");
 
      msg.setSubject ("Rosetta Code");
      msg.setContent ("Sending mail from C++ using POCO C++ Libraries");
 
      SMTPClientSession smtp ("mail.example.com"); // SMTP server name
      smtp.login ();
      smtp.sendMessage (msg);
      smtp.close ();
      std::cerr << "Sent mail successfully!" << std::endl;
    }
  catch (std::exception &e)
    {
      std::cerr << "failed to send mail: " << e.what() << std::endl;
      return EXIT_FAILURE;
    }
 
  return EXIT_SUCCESS;
}

C#

static void Main(string[] args)
{
    //First of all construct the SMTP client
 
    SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details
    SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false.
    SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
    SMTP.Credentials = new NetworkCredential("YourUserName", "YourPassword");
    MailMessage Mail = new MailMessage("[email protected]", "[email protected]");
 
 
    //Then we construct the message
 
    Mail.Subject = "Important Message";
    Mail.Body = "Hello over there"; //The body contains the string for your email
    //using "Mail.IsBodyHtml = true;" you can put an HTML page in your message body
 
    //Then we use the SMTP client to send the message
 
    SMTP.Send(Mail);
 
    Console.WriteLine("Message Sent");
}

Go

package main
 
import (
	"bufio"
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"net/smtp"
	"os"
	"strings"
)
 
type Message struct {
	From    string
	To      []string
	Cc      []string
	Subject string
	Content string
}
 
func (m Message) Bytes() (r []byte) {
	to := strings.Join(m.To, ",")
	cc := strings.Join(m.Cc, ",")
 
	r = append(r, []byte("From: "+m.From+"\n")...)
	r = append(r, []byte("To: "+to+"\n")...)
	r = append(r, []byte("Cc: "+cc+"\n")...)
	r = append(r, []byte("Subject: "+m.Subject+"\n\n")...)
	r = append(r, []byte(m.Content)...)
 
	return
}
 
func (m Message) Send(host string, port int, user, pass string) (err error) {
	err = check(host, user, pass)
	if err != nil {
		return
	}
 
	err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port),
		smtp.PlainAuth("", user, pass, host),
		m.From,
		m.To,
		m.Bytes(),
	)
 
	return
}
 
func check(host, user, pass string) error {
	if host == "" {
		return errors.New("Bad host")
	}
	if user == "" {
		return errors.New("Bad username")
	}
	if pass == "" {
		return errors.New("Bad password")
	}
 
	return nil
}
 
func main() {
	var flags struct {
		host string
		port int
		user string
		pass string
	}
	flag.StringVar(&flags.host, "host", "", "SMTP server to connect to")
	flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on")
	flag.StringVar(&flags.user, "user", "", "Username to authenticate with")
	flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with")
	flag.Parse()
 
	err := check(flags.host, flags.user, flags.pass)
	if err != nil {
		flag.Usage()
		os.Exit(1)
	}
 
	bufin := bufio.NewReader(os.Stdin)
 
	fmt.Printf("From: ")
	from, err := bufin.ReadString('\n')
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
	from = strings.Trim(from, " \t\n\r")
 
	var to []string
	for {
		fmt.Printf("To (Blank to finish): ")
		tmp, err := bufin.ReadString('\n')
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			os.Exit(1)
		}
		tmp = strings.Trim(tmp, " \t\n\r")
 
		if tmp == "" {
			break
		}
 
		to = append(to, tmp)
	}
 
	var cc []string
	for {
		fmt.Printf("Cc (Blank to finish): ")
		tmp, err := bufin.ReadString('\n')
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			os.Exit(1)
		}
		tmp = strings.Trim(tmp, " \t\n\r")
 
		if tmp == "" {
			break
		}
 
		cc = append(cc, tmp)
	}
 
	fmt.Printf("Subject: ")
	subject, err := bufin.ReadString('\n')
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
	subject = strings.Trim(subject, " \t\n\r")
 
	fmt.Printf("Content (Until EOF):\n")
	content, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
	content = bytes.Trim(content, " \t\n\r")
 
	m := Message{
		From:    from,
		To:      to,
		Cc:      cc,
		Subject: subject,
		Content: string(content),
	}
 
	fmt.Printf("\nSending message...\n")
	err = m.Send(flags.host, flags.port, flags.user, flags.pass)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
 
	fmt.Printf("Message sent.\n")
}

Java

import java.util.Properties;
 
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
/**
 * Mail
 */
public class Mail
{
 /**
  * Session
  */
 protected Session session;
 
 /**
  * Mail constructor.
  * 
  * @param host Host
  */
 public Mail(String host)
 {
  Properties properties = new Properties();
  properties.put("mail.smtp.host", host);
  session = Session.getDefaultInstance(properties);
 }
 
 /**
  * Send email message.
  *
  * @param from From
  * @param tos Recipients
  * @param ccs CC Recipients
  * @param subject Subject
  * @param text Text
  * @throws MessagingException
  */
 public void send(String from, String tos[], String ccs[], String subject,
        String text)
        throws MessagingException
 {
  MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  for (String to : tos)
   message.addRecipient(RecipientType.TO, new InternetAddress(to));
  for (String cc : ccs)
   message.addRecipient(RecipientType.TO, new InternetAddress(cc));
  message.setSubject(subject);
  message.setText(text);
  Transport.send(message);
 }
}

Kotlin

// version 1.1.4-3
 
import java.util.Properties
import javax.mail.Authenticator
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress
import javax.mail.Message.RecipientType
import javax.mail.Transport
 
fun sendEmail(user: String, tos: Array<String>, ccs: Array<String>, title: String,
              body: String, password: String) {
    val props = Properties()
    val host = "smtp.gmail.com"
    with (props) {
        put("mail.smtp.host", host)
        put("mail.smtp.port", "587") // for TLS
        put("mail.smtp.auth", "true")
        put("mail.smtp.starttls.enable", "true")
    }
    val auth = object: Authenticator() {
        protected override fun getPasswordAuthentication() =
            PasswordAuthentication(user, password)
    }
    val session = Session.getInstance(props, auth)
    val message = MimeMessage(session)
    with (message) {
        setFrom(InternetAddress(user))
        for (to in tos) addRecipient(RecipientType.TO, InternetAddress(to))
        for (cc in ccs) addRecipient(RecipientType.TO, InternetAddress(cc))
        setSubject(title)
        setText(body)
    }
    val transport = session.getTransport("smtp")
    with (transport) {
        connect(host, user, password)
        sendMessage(message, message.allRecipients)
        close()
    }
}
 
fun main(args: Array<String>) {
    val user = "[email protected]"
    val tos = arrayOf("[email protected]")
    val ccs = arrayOf<String>()
    val title = "Rosetta Code Example"
    val body = "This is just a test email"
    val password = "secret"
    sendEmail(user, tos, ccs, title, body, password)
}

PHP

mail('[email protected]', 'My Subject', "A Message!", "From: [email protected]");

Python

import smtplib
 
def sendemail(from_addr, to_addr_list, cc_addr_list,
              subject, message,
              login, password,
              smtpserver='smtp.gmail.com:587'):
    header  = 'From: %s\n' % from_addr
    header += 'To: %s\n' % ','.join(to_addr_list)
    header += 'Cc: %s\n' % ','.join(cc_addr_list)
    header += 'Subject: %s\n\n' % subject
    message = header + message
 
    server = smtplib.SMTP(smtpserver)
    server.starttls()
    server.login(login,password)
    problems = server.sendmail(from_addr, to_addr_list, message)
    server.quit()
    return problems

示例:

sendemail(from_addr    = '[email protected]', 
          to_addr_list = ['[email protected]'],
          cc_addr_list = ['[email protected]'], 
          subject      = 'Howdy', 
          message      = 'Howdy from a python function', 
          login        = 'pythonuser', 
          password     = 'XXXXX')

Ruby

require 'base64'
require 'net/smtp'
require 'tmail'
require 'mime/types'
 
class Email
  def initialize(from, to, subject, body, options={})
    @opts = {:attachments => [], :server => 'localhost'}.update(options)
    @msg = TMail::Mail.new
    @msg.from    = from
    @msg.to      = to
    @msg.subject = subject
    @msg.cc      = @opts[:cc]  if @opts[:cc]
    @msg.bcc     = @opts[:bcc] if @opts[:bcc]
 
    if @opts[:attachments].empty?
      # just specify the body
      @msg.body = body
    else
      # attach attachments, including the body
      @msg.body = "This is a multi-part message in MIME format.\n"
 
      msg_body = TMail::Mail.new
      msg_body.body = body
      msg_body.set_content_type("text","plain", {:charset => "ISO-8859-1"})
      @msg.parts << msg_body
 
      octet_stream = MIME::Types['application/octet-stream'].first
 
      @opts[:attachments].select {|file| File.readable?(file)}.each do |file|
        mime_type = MIME::Types.type_for(file).first || octet_stream
        @msg.parts << create_attachment(file, mime_type)
      end
    end
  end
  attr_reader :msg
 
  def create_attachment(file, mime_type)
    attach = TMail::Mail.new
    if mime_type.binary?
      attach.body = Base64.encode64(File.read(file))
      attach.transfer_encoding = 'base64'
    else
      attach.body = File.read(file)
    end
    attach.set_disposition("attachment", {:filename => file})
    attach.set_content_type(mime_type.media_type, mime_type.sub_type, {:name=>file})
    attach
  end
 
  # instance method to send an Email object
  def send
    args = @opts.values_at(:server, :port, :helo, :username, :password, :authtype)
    Net::SMTP.start(*args) do |smtp|
      smtp.send_message(@msg.to_s, @msg.from[0], @msg.to)
    end
  end
 
  # class method to construct an Email object and send it
  def self.send(*args)
    self.new(*args).send
  end
end
 
Email.send(
  '[email protected]',
  %w{ [email protected] [email protected] },
  'the subject',
  "the body\nhas lines",
  {
    :attachments => %w{ file1 file2 file3 },
    :server => 'mail.example.com',
    :helo => 'sender.invalid',
    :username => 'user',
    :password => 'secret'
  }
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章