瀏覽代碼

Working on Attach() function, Fixed function signatures, added very basic test, changed some struct signatures

Jordan 11 年之前
父節點
當前提交
543585516a
共有 2 個文件被更改,包括 54 次插入5 次删除
  1. 39 5
      email.go
  2. 15 0
      email_test.go

+ 39 - 5
email.go

@@ -3,8 +3,12 @@
 package email
 
 import (
+	"io/ioutil"
+	"log"
 	"net/mail"
 	"net/smtp"
+	"net/textproto"
+	"os"
 )
 
 //Email is the type used for email messages
@@ -13,18 +17,48 @@ type Email struct {
 	To          []string
 	Bcc         []string
 	Cc          []string
-	Subject     []string
-	Text        []byte //Plaintext message (optional)
-	Html        []byte //Html message (optional)
+	Subject     string
+	Text        string //Plaintext message (optional)
+	Html        string //Html message (optional)
 	Headers     []mail.Header
-	Attachments []Attachment //Might be a map soon - stay tuned.
+	Attachments map[string]*Attachment
+}
+
+func NewEmail() *Email {
+	return &Email{Attachments: make(map[string]*Attachment)}
+}
+
+//Attach is used to attach a file to the email.
+//It attempts to open the file reference by filename and, if successful, creates an Attachment.
+//This Attachment is then appended to the slice of Email.Attachments.
+//The function will then return the Attachment for reference, as well as nil for the error if successful.
+func (e *Email) Attach(filename string) (a *Attachment, err error) {
+	//Check if the file exists, return any error
+	if _, err := os.Stat(filename); os.IsNotExist(err) {
+		log.Fatal("%s does not exist", filename)
+		return nil, err
+	}
+	buffer, _ := ioutil.ReadFile(filename)
+	e.Attachments[filename] = &Attachment{
+		Filename: filename,
+		Header:   textproto.MIMEHeader{},
+		Content:  buffer}
+	return e.Attachments[filename], nil
+}
+
+func (e *Email) Bytes() []byte {
+	return []byte{}
 }
 
 //Send an email using the given host and SMTP auth (optional)
-func (e Email) Send(addr string, a smtp.Auth, e Email) {
+func (e *Email) Send(addr string, a smtp.Auth) {
 
 }
 
+//Attachment is a struct representing an email attachment
+//Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
 type Attachment struct {
 	Filename string
+	Header   textproto.MIMEHeader
+	Content  []byte
 }

+ 15 - 0
email_test.go

@@ -0,0 +1,15 @@
+package email
+
+import (
+	"testing"
+)
+
+func TestEmail(*testing.T) {
+	e := NewEmail()
+	e.To = []string{"test@example.com"}
+	e.Bcc = []string{"test_bcc@example.com"}
+	e.Cc = []string{"test_cc@example.com"}
+	e.Subject = "Awesome Subject"
+	e.Text = "Text Body is, of course, supported!"
+	e.Html = "<h1>Fancy Html is supported, too!</h1>"
+}