How to use New method of smtp Package

Best Venom code snippet using smtp.New

mta_test.go

Source:mta_test.go Github

copy

Full Screen

...68}69func (p *testProtocol) StartTls(c *tls.Config) error {70 if !p.expectTLS {71 p.t.Fatalf("Did not expect StartTls")72 return errors.New("NOT IMPLEMENTED")73 }74 return nil75}76func (p *testProtocol) GetIP() net.IP {77 return net.ParseIP("127.0.0.1")78}79func (p *testProtocol) GetState() *smtp.State {80 return &p.state81}82// Tests answers for HELO,EHLO and QUIT83func TestAnswersHeloQuit(t *testing.T) {84 cfg := Config{85 Hostname: "home.sweet.home",86 }87 mta := New(cfg, HandlerFunc(dummyHandler))88 if mta == nil {89 t.Fatal("Could not create mta server")90 }91 c.Convey("Testing answers for HELO and QUIT.", t, func(ctx c.C) {92 // Test connection with HELO and QUIT93 proto := &testProtocol{94 t: t,95 ctx: ctx,96 cmds: []smtp.Cmd{97 smtp.HeloCmd{98 Domain: "some.sender",99 },100 smtp.QuitCmd{},101 },102 answers: []interface{}{103 smtp.Answer{104 Status: smtp.Ready,105 Message: cfg.Hostname + " Service Ready",106 },107 smtp.Answer{108 Status: smtp.Ok,109 Message: cfg.Hostname,110 },111 smtp.Answer{112 Status: smtp.Closing,113 Message: "Bye!",114 },115 },116 }117 mta.HandleClient(proto)118 c.So(proto.GetState().Hostname, c.ShouldEqual, "some.sender")119 })120 c.Convey("Testing answers for HELO and close connection.", t, func(ctx c.C) {121 proto := &testProtocol{122 t: t,123 ctx: ctx,124 cmds: []smtp.Cmd{125 smtp.HeloCmd{126 Domain: "some.sender",127 },128 nil,129 },130 answers: []interface{}{131 smtp.Answer{132 Status: smtp.Ready,133 Message: cfg.Hostname + " Service Ready",134 },135 smtp.Answer{136 Status: smtp.Ok,137 Message: cfg.Hostname,138 },139 },140 }141 mta.HandleClient(proto)142 })143 c.Convey("Testing answers for EHLO and QUIT.", t, func(ctx c.C) {144 // Test connection with EHLO and QUIT145 proto := &testProtocol{146 t: t,147 ctx: ctx,148 cmds: []smtp.Cmd{149 smtp.EhloCmd{150 Domain: "some.sender",151 },152 smtp.QuitCmd{},153 },154 answers: []interface{}{155 smtp.Answer{156 Status: smtp.Ready,157 Message: cfg.Hostname + " Service Ready",158 },159 smtp.MultiAnswer{160 Status: smtp.Ok,161 },162 smtp.Answer{163 Status: smtp.Closing,164 Message: "Bye!",165 },166 },167 }168 mta.HandleClient(proto)169 })170 c.Convey("Testing answers for EHLO and close connection.", t, func(ctx c.C) {171 proto := &testProtocol{172 t: t,173 ctx: ctx,174 cmds: []smtp.Cmd{175 smtp.EhloCmd{176 Domain: "some.sender.ehlo",177 },178 nil,179 },180 answers: []interface{}{181 smtp.Answer{182 Status: smtp.Ready,183 Message: cfg.Hostname + " Service Ready",184 },185 smtp.MultiAnswer{186 Status: smtp.Ok,187 },188 },189 }190 mta.HandleClient(proto)191 c.So(proto.GetState().Hostname, c.ShouldEqual, "some.sender.ehlo")192 })193}194// Test answers if we are given a sequence of MAIL,RCPT,DATA commands.195func TestMailAnswersCorrectSequence(t *testing.T) {196 cfg := Config{197 Hostname: "home.sweet.home",198 }199 mta := New(cfg, HandlerFunc(dummyHandler))200 if mta == nil {201 t.Fatal("Could not create mta server")202 }203 c.Convey("Testing correct sequence of MAIL,RCPT,DATA commands.", t, func(ctx c.C) {204 proto := &testProtocol{205 t: t,206 ctx: ctx,207 cmds: []smtp.Cmd{208 smtp.HeloCmd{209 Domain: "some.sender",210 },211 smtp.MailCmd{212 From: getMailWithoutError("someone@somewhere.test"),213 },214 smtp.RcptCmd{215 To: getMailWithoutError("guy1@somewhere.test"),216 },217 smtp.RcptCmd{218 To: getMailWithoutError("guy2@somewhere.test"),219 },220 smtp.DataCmd{221 R: *smtp.NewDataReader(bufio.NewReader(bytes.NewReader([]byte("Some test email\n.\n")))),222 },223 smtp.QuitCmd{},224 },225 answers: []interface{}{226 smtp.Answer{227 Status: smtp.Ready,228 Message: cfg.Hostname + " Service Ready",229 },230 smtp.Answer{231 Status: smtp.Ok,232 Message: cfg.Hostname,233 },234 smtp.Answer{235 Status: smtp.Ok,236 Message: "OK",237 },238 smtp.Answer{239 Status: smtp.Ok,240 Message: "OK",241 },242 smtp.Answer{243 Status: smtp.Ok,244 Message: "OK",245 },246 smtp.Answer{247 Status: smtp.StartData,248 Message: "OK",249 },250 smtp.Answer{251 Status: smtp.Ok,252 Message: "OK",253 },254 smtp.Answer{255 Status: smtp.Closing,256 Message: "Bye!",257 },258 },259 }260 mta.HandleClient(proto)261 })262 c.Convey("Testing wrong sequence of MAIL,RCPT,DATA commands.", t, func(ctx c.C) {263 c.Convey("RCPT before MAIL", func() {264 proto := &testProtocol{265 t: t,266 ctx: ctx,267 cmds: []smtp.Cmd{268 smtp.HeloCmd{269 Domain: "some.sender",270 },271 smtp.RcptCmd{272 To: getMailWithoutError("guy1@somewhere.test"),273 },274 smtp.QuitCmd{},275 },276 answers: []interface{}{277 smtp.Answer{278 Status: smtp.Ready,279 Message: cfg.Hostname + " Service Ready",280 },281 smtp.Answer{282 Status: smtp.Ok,283 Message: cfg.Hostname,284 },285 smtp.Answer{286 Status: smtp.BadSequence,287 Message: "Need mail before RCPT",288 },289 smtp.Answer{290 Status: smtp.Closing,291 Message: "Bye!",292 },293 },294 }295 mta.HandleClient(proto)296 })297 c.Convey("DATA before MAIL", func() {298 proto := &testProtocol{299 t: t,300 ctx: ctx,301 cmds: []smtp.Cmd{302 smtp.HeloCmd{303 Domain: "some.sender",304 },305 smtp.DataCmd{},306 smtp.QuitCmd{},307 },308 answers: []interface{}{309 smtp.Answer{310 Status: smtp.Ready,311 Message: cfg.Hostname + " Service Ready",312 },313 smtp.Answer{314 Status: smtp.Ok,315 Message: cfg.Hostname,316 },317 smtp.Answer{318 Status: smtp.BadSequence,319 Message: "Need mail before DATA",320 },321 smtp.Answer{322 Status: smtp.Closing,323 Message: "Bye!",324 },325 },326 }327 mta.HandleClient(proto)328 })329 c.Convey("DATA before RCPT", func() {330 proto := &testProtocol{331 t: t,332 ctx: ctx,333 cmds: []smtp.Cmd{334 smtp.HeloCmd{335 Domain: "some.sender",336 },337 smtp.MailCmd{338 From: getMailWithoutError("guy@somewhere.test"),339 },340 smtp.DataCmd{},341 smtp.QuitCmd{},342 },343 answers: []interface{}{344 smtp.Answer{345 Status: smtp.Ready,346 Message: cfg.Hostname + " Service Ready",347 },348 smtp.Answer{349 Status: smtp.Ok,350 Message: cfg.Hostname,351 },352 smtp.Answer{353 Status: smtp.Ok,354 Message: "OK",355 },356 smtp.Answer{357 Status: smtp.BadSequence,358 Message: "Need RCPT before DATA",359 },360 smtp.Answer{361 Status: smtp.Closing,362 Message: "Bye!",363 },364 },365 }366 mta.HandleClient(proto)367 })368 c.Convey("Multiple MAIL commands.", func() {369 proto := &testProtocol{370 t: t,371 ctx: ctx,372 cmds: []smtp.Cmd{373 smtp.HeloCmd{374 Domain: "some.sender",375 },376 smtp.MailCmd{377 From: getMailWithoutError("guy@somewhere.test"),378 },379 smtp.RcptCmd{380 To: getMailWithoutError("someone@somewhere.test"),381 },382 smtp.MailCmd{383 From: getMailWithoutError("someguy@somewhere.test"),384 },385 smtp.QuitCmd{},386 },387 answers: []interface{}{388 smtp.Answer{389 Status: smtp.Ready,390 Message: cfg.Hostname + " Service Ready",391 },392 smtp.Answer{393 Status: smtp.Ok,394 Message: cfg.Hostname,395 },396 smtp.Answer{397 Status: smtp.Ok,398 Message: "OK",399 },400 smtp.Answer{401 Status: smtp.Ok,402 Message: "OK",403 },404 smtp.Answer{405 Status: smtp.BadSequence,406 Message: "Sender already specified",407 },408 smtp.Answer{409 Status: smtp.Closing,410 Message: "Bye!",411 },412 },413 }414 mta.HandleClient(proto)415 })416 })417}418// Tests if our state gets reset correctly.419func TestReset(t *testing.T) {420 cfg := Config{421 Hostname: "home.sweet.home",422 }423 mta := New(cfg, HandlerFunc(dummyHandler))424 if mta == nil {425 t.Fatal("Could not create mta server")426 }427 c.Convey("Testing reset", t, func(ctx c.C) {428 c.Convey("Test reset after sending mail.", func() {429 proto := &testProtocol{430 t: t,431 ctx: ctx,432 cmds: []smtp.Cmd{433 smtp.HeloCmd{434 Domain: "some.sender",435 },436 smtp.MailCmd{437 From: getMailWithoutError("someone@somewhere.test"),438 },439 smtp.RcptCmd{440 To: getMailWithoutError("guy1@somewhere.test"),441 },442 smtp.DataCmd{443 R: *smtp.NewDataReader(bufio.NewReader(bytes.NewReader([]byte("Some email content\n.\n")))),444 },445 smtp.RcptCmd{446 To: getMailWithoutError("someguy@somewhere.test"),447 },448 smtp.QuitCmd{},449 },450 answers: []interface{}{451 smtp.Answer{452 Status: smtp.Ready,453 Message: cfg.Hostname + " Service Ready",454 },455 smtp.Answer{456 Status: smtp.Ok,457 Message: cfg.Hostname,458 },459 smtp.Answer{460 Status: smtp.Ok,461 Message: "OK",462 },463 smtp.Answer{464 Status: smtp.Ok,465 Message: "OK",466 },467 smtp.Answer{468 Status: smtp.StartData,469 Message: "OK",470 },471 smtp.Answer{472 Status: smtp.Ok,473 Message: "OK",474 },475 smtp.Answer{476 Status: smtp.BadSequence,477 Message: "Need mail before RCPT",478 },479 smtp.Answer{480 Status: smtp.Closing,481 Message: "Bye!",482 },483 },484 }485 mta.HandleClient(proto)486 })487 c.Convey("Manually reset", func() {488 proto := &testProtocol{489 t: t,490 ctx: ctx,491 cmds: []smtp.Cmd{492 smtp.HeloCmd{493 Domain: "some.sender",494 },495 smtp.MailCmd{496 From: getMailWithoutError("someone@somewhere.test"),497 },498 smtp.RcptCmd{499 To: getMailWithoutError("guy1@somewhere.test"),500 },501 smtp.RsetCmd{},502 smtp.MailCmd{503 From: getMailWithoutError("someone@somewhere.test"),504 },505 smtp.RcptCmd{506 To: getMailWithoutError("guy1@somewhere.test"),507 },508 smtp.DataCmd{509 R: *smtp.NewDataReader(bufio.NewReader(bytes.NewReader([]byte("Some email\n.\n")))),510 },511 smtp.QuitCmd{},512 },513 answers: []interface{}{514 smtp.Answer{515 Status: smtp.Ready,516 Message: cfg.Hostname + " Service Ready",517 },518 smtp.Answer{519 Status: smtp.Ok,520 Message: cfg.Hostname,521 },522 smtp.Answer{523 Status: smtp.Ok,524 Message: "OK",525 },526 smtp.Answer{527 Status: smtp.Ok,528 Message: "OK",529 },530 smtp.Answer{531 Status: smtp.Ok,532 Message: "OK",533 },534 smtp.Answer{535 Status: smtp.Ok,536 Message: "OK",537 },538 smtp.Answer{539 Status: smtp.Ok,540 Message: "OK",541 },542 smtp.Answer{543 Status: smtp.StartData,544 Message: "OK",545 },546 smtp.Answer{547 Status: smtp.Ok,548 Message: "OK",549 },550 smtp.Answer{551 Status: smtp.Closing,552 Message: "Bye!",553 },554 },555 }556 mta.HandleClient(proto)557 })558 // EHLO should reset state.559 c.Convey("Reset with EHLO", func() {560 proto := &testProtocol{561 t: t,562 ctx: ctx,563 cmds: []smtp.Cmd{564 smtp.EhloCmd{565 Domain: "some.sender",566 },567 smtp.MailCmd{568 From: getMailWithoutError("someone@somewhere.test"),569 },570 smtp.RcptCmd{571 To: getMailWithoutError("guy1@somewhere.test"),572 },573 smtp.EhloCmd{574 Domain: "some.sender",575 },576 smtp.MailCmd{577 From: getMailWithoutError("someone@somewhere.test"),578 },579 smtp.RcptCmd{580 To: getMailWithoutError("guy1@somewhere.test"),581 },582 smtp.DataCmd{583 R: *smtp.NewDataReader(bufio.NewReader(bytes.NewReader([]byte("Some email\n.\n")))),584 },585 smtp.QuitCmd{},586 },587 answers: []interface{}{588 smtp.Answer{589 Status: smtp.Ready,590 Message: cfg.Hostname + " Service Ready",591 },592 smtp.MultiAnswer{593 Status: smtp.Ok,594 },595 smtp.Answer{596 Status: smtp.Ok,597 Message: "OK",598 },599 smtp.Answer{600 Status: smtp.Ok,601 Message: "OK",602 },603 smtp.MultiAnswer{604 Status: smtp.Ok,605 },606 smtp.Answer{607 Status: smtp.Ok,608 Message: "OK",609 },610 smtp.Answer{611 Status: smtp.Ok,612 Message: "OK",613 },614 smtp.Answer{615 Status: smtp.StartData,616 Message: "OK",617 },618 smtp.Answer{619 Status: smtp.Ok,620 Message: "OK",621 },622 smtp.Answer{623 Status: smtp.Closing,624 Message: "Bye!",625 },626 },627 }628 mta.HandleClient(proto)629 })630 })631}632// Tests answers if we send an unknown command.633func TestAnswersUnknownCmd(t *testing.T) {634 cfg := Config{635 Hostname: "home.sweet.home",636 }637 mta := New(cfg, HandlerFunc(dummyHandler))638 if mta == nil {639 t.Fatal("Could not create mta server")640 }641 c.Convey("Testing answers for unknown cmds.", t, func(ctx c.C) {642 proto := &testProtocol{643 t: t,644 ctx: ctx,645 cmds: []smtp.Cmd{646 smtp.HeloCmd{647 Domain: "some.sender",648 },649 smtp.UnknownCmd{650 Cmd: "someinvalidcmd",651 },652 smtp.QuitCmd{},653 },654 answers: []interface{}{655 smtp.Answer{656 Status: smtp.Ready,657 Message: cfg.Hostname + " Service Ready",658 },659 smtp.Answer{660 Status: smtp.Ok,661 Message: "OK",662 },663 smtp.Answer{664 Status: smtp.SyntaxError,665 Message: cfg.Hostname,666 },667 smtp.Answer{668 Status: smtp.Closing,669 Message: "Bye!",670 },671 },672 }673 mta.HandleClient(proto)674 })675}676// Tests STARTTLS677func TestStartTls(t *testing.T) {678 cfg := Config{679 Hostname: "home.sweet.home",680 }681 mta := New(cfg, HandlerFunc(dummyHandler))682 mta.TlsConfig = &tls.Config{}683 if mta == nil {684 t.Fatal("Could not create mta server")685 }686 c.Convey("Testing STARTTLS", t, func(ctx c.C) {687 proto := &testProtocol{688 t: t,689 ctx: ctx,690 cmds: []smtp.Cmd{691 smtp.EhloCmd{692 Domain: "some.sender",693 },694 smtp.StartTlsCmd{},695 smtp.QuitCmd{},696 },697 answers: []interface{}{698 smtp.Answer{699 Status: smtp.Ready,700 Message: cfg.Hostname + " Service Ready",701 },702 smtp.MultiAnswer{703 Status: smtp.Ok,704 },705 smtp.Answer{706 Status: smtp.Ready,707 },708 smtp.Answer{709 Status: smtp.Closing,710 Message: "Bye!",711 },712 },713 }714 proto.expectTLS = true715 mta.HandleClient(proto)716 })717 c.Convey("Testing if STARTTLS resets state", t, func(ctx c.C) {718 proto := &testProtocol{719 t: t,720 ctx: ctx,721 cmds: []smtp.Cmd{722 smtp.EhloCmd{723 Domain: "some.sender",724 },725 smtp.MailCmd{726 From: getMailWithoutError("someone@somewhere.test"),727 },728 smtp.StartTlsCmd{},729 smtp.MailCmd{730 From: getMailWithoutError("someone@somewhere.test"),731 },732 smtp.QuitCmd{},733 },734 answers: []interface{}{735 smtp.Answer{736 Status: smtp.Ready,737 Message: cfg.Hostname + " Service Ready",738 },739 smtp.MultiAnswer{740 Status: smtp.Ok,741 },742 smtp.Answer{743 Status: smtp.Ok,744 },745 smtp.Answer{746 Status: smtp.Ready,747 },748 smtp.Answer{749 Status: smtp.Ok,750 },751 smtp.Answer{752 Status: smtp.Closing,753 Message: "Bye!",754 },755 },756 }757 proto.expectTLS = true758 mta.HandleClient(proto)759 })760 c.Convey("Testing if we can STARTTLS twice", t, func(ctx c.C) {761 proto := &testProtocol{762 t: t,763 ctx: ctx,764 cmds: []smtp.Cmd{765 smtp.EhloCmd{766 Domain: "some.sender",767 },768 smtp.StartTlsCmd{},769 smtp.StartTlsCmd{},770 smtp.QuitCmd{},771 },772 answers: []interface{}{773 smtp.Answer{774 Status: smtp.Ready,775 Message: cfg.Hostname + " Service Ready",776 },777 smtp.MultiAnswer{778 Status: smtp.Ok,779 },780 smtp.Answer{781 Status: smtp.Ready,782 },783 smtp.Answer{784 Status: smtp.NotImplemented,785 },786 smtp.Answer{787 Status: smtp.Closing,788 Message: "Bye!",789 },790 },791 }792 proto.expectTLS = true793 mta.HandleClient(proto)794 })795}796// Simple test for representation of SessionId797func TestSessionId(t *testing.T) {798 c.Convey("Testing Session ID String()", t, func() {799 id := smtp.Id{Timestamp: 1446302030, Counter: 42}800 c.So(id.String(), c.ShouldEqual, "5634d14e2a")801 id = smtp.Id{Timestamp: 2147483648, Counter: 4294967295}802 c.So(id.String(), c.ShouldEqual, "80000000ffffffff")803 })804}805// Test whether error in handle() is correctly handled in the DATA command806func TestErrorInHandler(t *testing.T) {807 cfg := Config{808 Hostname: "home.sweet.home",809 }810 mta := New(cfg, HandlerFunc(dummyHandlerError))811 if mta == nil {812 t.Fatal("Could not create mta server")813 }814 c.Convey("Testing with error in handle()", t, func(ctx c.C) {815 proto := &testProtocol{816 t: t,817 ctx: ctx,818 cmds: []smtp.Cmd{819 smtp.HeloCmd{820 Domain: "some.sender",821 },822 smtp.MailCmd{823 From: getMailWithoutError("someone@somewhere.test"),824 },825 smtp.RcptCmd{826 To: getMailWithoutError("guy1@somewhere.test"),827 },828 smtp.DataCmd{829 R: *smtp.NewDataReader(bufio.NewReader(bytes.NewReader([]byte("Some test email\n.\n")))),830 },831 smtp.QuitCmd{},832 },833 answers: []interface{}{834 smtp.Answer{835 Status: smtp.Ready,836 Message: cfg.Hostname + " Service Ready",837 },838 smtp.Answer{839 Status: smtp.Ok,840 Message: cfg.Hostname,841 },842 smtp.Answer{843 Status: smtp.Ok,...

Full Screen

Full Screen

mail.go

Source:mail.go Github

copy

Full Screen

...60 return &loginAuth{username, password, host}61}62func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {63 if !server.TLS {64 return "", nil, errors.New("unencrypted connection")65 }66 if server.Name != a.host {67 return "", nil, errors.New("wrong host name")68 }69 return "LOGIN", []byte{}, nil70}71func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {72 if more {73 switch string(fromServer) {74 case "Username:":75 return []byte(a.username), nil76 case "Password:":77 return []byte(a.password), nil78 default:79 return nil, errors.New("Unknown fromServer")80 }81 }82 return nil, nil83}84func ConnectToSMTPServerAdvanced(connectionInfo *SmtpConnectionInfo) (net.Conn, *model.AppError) {85 var conn net.Conn86 var err error87 smtpAddress := connectionInfo.SmtpServerHost + ":" + connectionInfo.SmtpPort88 if connectionInfo.ConnectionSecurity == model.CONN_SECURITY_TLS {89 tlsconfig := &tls.Config{90 InsecureSkipVerify: connectionInfo.SkipCertVerification,91 ServerName: connectionInfo.SmtpServerName,92 }93 conn, err = tls.Dial("tcp", smtpAddress, tlsconfig)94 if err != nil {95 return nil, model.NewAppError("SendMail", "utils.mail.connect_smtp.open_tls.app_error", nil, err.Error(), http.StatusInternalServerError)96 }97 } else {98 conn, err = net.Dial("tcp", smtpAddress)99 if err != nil {100 return nil, model.NewAppError("SendMail", "utils.mail.connect_smtp.open.app_error", nil, err.Error(), http.StatusInternalServerError)101 }102 }103 return conn, nil104}105func ConnectToSMTPServer(config *model.Config) (net.Conn, *model.AppError) {106 return ConnectToSMTPServerAdvanced(107 &SmtpConnectionInfo{108 ConnectionSecurity: *config.EmailSettings.ConnectionSecurity,109 SkipCertVerification: *config.EmailSettings.SkipServerCertificateVerification,110 SmtpServerName: *config.EmailSettings.SMTPServer,111 SmtpServerHost: *config.EmailSettings.SMTPServer,112 SmtpPort: *config.EmailSettings.SMTPPort,113 },114 )115}116func NewSMTPClientAdvanced(conn net.Conn, hostname string, connectionInfo *SmtpConnectionInfo) (*smtp.Client, *model.AppError) {117 c, err := smtp.NewClient(conn, connectionInfo.SmtpServerName+":"+connectionInfo.SmtpPort)118 if err != nil {119 mlog.Error("Failed to open a connection to SMTP server", mlog.Err(err))120 return nil, model.NewAppError("SendMail", "utils.mail.connect_smtp.open_tls.app_error", nil, err.Error(), http.StatusInternalServerError)121 }122 if hostname != "" {123 err = c.Hello(hostname)124 if err != nil {125 mlog.Error("Failed to to set the HELO to SMTP server", mlog.Err(err))126 return nil, model.NewAppError("SendMail", "utils.mail.connect_smtp.helo.app_error", nil, err.Error(), http.StatusInternalServerError)127 }128 }129 if connectionInfo.ConnectionSecurity == model.CONN_SECURITY_STARTTLS {130 tlsconfig := &tls.Config{131 InsecureSkipVerify: connectionInfo.SkipCertVerification,132 ServerName: connectionInfo.SmtpServerName,133 }134 c.StartTLS(tlsconfig)135 }136 if connectionInfo.Auth {137 if err = c.Auth(&authChooser{connectionInfo: connectionInfo}); err != nil {138 return nil, model.NewAppError("SendMail", "utils.mail.new_client.auth.app_error", nil, err.Error(), http.StatusInternalServerError)139 }140 }141 return c, nil142}143func NewSMTPClient(conn net.Conn, config *model.Config) (*smtp.Client, *model.AppError) {144 return NewSMTPClientAdvanced(145 conn,146 utils.GetHostnameFromSiteURL(*config.ServiceSettings.SiteURL),147 &SmtpConnectionInfo{148 ConnectionSecurity: *config.EmailSettings.ConnectionSecurity,149 SkipCertVerification: *config.EmailSettings.SkipServerCertificateVerification,150 SmtpServerName: *config.EmailSettings.SMTPServer,151 SmtpServerHost: *config.EmailSettings.SMTPServer,152 SmtpPort: *config.EmailSettings.SMTPPort,153 Auth: *config.EmailSettings.EnableSMTPAuth,154 SmtpUsername: *config.EmailSettings.SMTPUsername,155 SmtpPassword: *config.EmailSettings.SMTPPassword,156 },157 )158}159func TestConnection(config *model.Config) {160 if !*config.EmailSettings.SendEmailNotifications {161 return162 }163 conn, err1 := ConnectToSMTPServer(config)164 if err1 != nil {165 mlog.Error("SMTP server settings do not appear to be configured properly", mlog.Err(err1))166 return167 }168 defer conn.Close()169 c, err2 := NewSMTPClient(conn, config)170 if err2 != nil {171 mlog.Error("SMTP server settings do not appear to be configured properly", mlog.Err(err2))172 return173 }174 defer c.Quit()175 defer c.Close()176}177func SendMailUsingConfig(to, subject, htmlBody string, config *model.Config, enableComplianceFeatures bool) *model.AppError {178 fromMail := mail.Address{Name: *config.EmailSettings.FeedbackName, Address: *config.EmailSettings.FeedbackEmail}179 replyTo := mail.Address{Name: *config.EmailSettings.FeedbackName, Address: *config.EmailSettings.ReplyToAddress}180 return SendMailUsingConfigAdvanced(to, to, fromMail, replyTo, subject, htmlBody, nil, nil, nil, config, enableComplianceFeatures)181}182// allows for sending an email with attachments and differing MIME/SMTP recipients183func SendMailUsingConfigAdvanced(mimeTo, smtpTo string, from, replyTo mail.Address, subject, htmlBody string, attachments []*model.FileInfo, embeddedFiles map[string]io.Reader, mimeHeaders map[string]string, config *model.Config, enableComplianceFeatures bool) *model.AppError {184 if len(*config.EmailSettings.SMTPServer) == 0 {185 return nil186 }187 conn, err := ConnectToSMTPServer(config)188 if err != nil {189 return err190 }191 defer conn.Close()192 c, err := NewSMTPClient(conn, config)193 if err != nil {194 return err195 }196 defer c.Quit()197 defer c.Close()198 fileBackend, err := filesstore.NewFileBackend(&config.FileSettings, enableComplianceFeatures)199 if err != nil {200 return err201 }202 return SendMail(c, mimeTo, smtpTo, from, replyTo, subject, htmlBody, attachments, embeddedFiles, mimeHeaders, fileBackend, time.Now())203}204func SendMail(c smtpClient, mimeTo, smtpTo string, from, replyTo mail.Address, subject, htmlBody string, attachments []*model.FileInfo, embeddedFiles map[string]io.Reader, mimeHeaders map[string]string, fileBackend filesstore.FileBackend, date time.Time) *model.AppError {205 mlog.Debug("sending mail", mlog.String("to", smtpTo), mlog.String("subject", subject))206 htmlMessage := "\r\n<html><body>" + htmlBody + "</body></html>"207 txtBody, err := html2text.FromString(htmlBody)208 if err != nil {209 mlog.Warn("Unable to convert html body to text", mlog.Err(err))210 txtBody = ""211 }212 headers := map[string][]string{213 "From": {from.String()},214 "To": {mimeTo},215 "Subject": {encodeRFC2047Word(subject)},216 "Content-Transfer-Encoding": {"8bit"},217 "Auto-Submitted": {"auto-generated"},218 "Precedence": {"bulk"},219 }220 if len(replyTo.Address) > 0 {221 headers["Reply-To"] = []string{replyTo.String()}222 }223 for k, v := range mimeHeaders {224 headers[k] = []string{encodeRFC2047Word(v)}225 }226 m := gomail.NewMessage(gomail.SetCharset("UTF-8"))227 m.SetHeaders(headers)228 m.SetDateHeader("Date", date)229 m.SetBody("text/plain", txtBody)230 m.AddAlternative("text/html", htmlMessage)231 for name, reader := range embeddedFiles {232 m.EmbedReader(name, reader)233 }234 for _, fileInfo := range attachments {235 bytes, err := fileBackend.ReadFile(fileInfo.Path)236 if err != nil {237 return err238 }239 m.Attach(fileInfo.Name, gomail.SetCopyFunc(func(writer io.Writer) error {240 if _, err := writer.Write(bytes); err != nil {241 return model.NewAppError("SendMail", "utils.mail.sendMail.attachments.write_error", nil, err.Error(), http.StatusInternalServerError)242 }243 return nil244 }))245 }246 if err = c.Mail(from.Address); err != nil {247 return model.NewAppError("SendMail", "utils.mail.send_mail.from_address.app_error", nil, err.Error(), http.StatusInternalServerError)248 }249 if err = c.Rcpt(smtpTo); err != nil {250 return model.NewAppError("SendMail", "utils.mail.send_mail.to_address.app_error", nil, err.Error(), http.StatusInternalServerError)251 }252 w, err := c.Data()253 if err != nil {254 return model.NewAppError("SendMail", "utils.mail.send_mail.msg_data.app_error", nil, err.Error(), http.StatusInternalServerError)255 }256 _, err = m.WriteTo(w)257 if err != nil {258 return model.NewAppError("SendMail", "utils.mail.send_mail.msg.app_error", nil, err.Error(), http.StatusInternalServerError)259 }260 err = w.Close()261 if err != nil {262 return model.NewAppError("SendMail", "utils.mail.send_mail.close.app_error", nil, err.Error(), http.StatusInternalServerError)263 }264 return nil265}...

Full Screen

Full Screen

service.go

Source:service.go Github

copy

Full Screen

...5 "github.com/jitsucom/jitsu/server/logging"6 "github.com/pkg/errors"7 gomail "gopkg.in/mail.v2"8)9var ErrSMTPNotConfigured = errors.New("SMTP isn't configured")10type SMTPConfiguration struct {11 Host string `json:"host"`12 Port int `json:"port"`13 User string `json:"user"`14 Password string `json:"password"`15 From string `json:"from"`16 Signature string `json:"signature"`17 ReplyTo string `json:"reply_to"`18}19func (sc *SMTPConfiguration) Validate() error {20 if sc.Host == "" {21 return errors.New("smtp host is required")22 }23 if sc.Port == 0 {24 return errors.New("smtp port is required")25 }26 if sc.User == "" {27 return errors.New("smtp user is required")28 }29 if sc.From == "" {30 sc.From = "support@jitsu.com"31 }32 if sc.Signature == "" {33 sc.Signature = "Your Jitsu - an open-source data collection platform team"34 }35 return nil36}37type Service struct {38 smtp *SMTPConfiguration39 templates map[templateSubject]*template.Template40}41func NewService(smtp *SMTPConfiguration) (*Service, error) {42 if smtp == nil {43 return nil, nil44 }45 logging.Info("Initializing SMTP email service..")46 if sc, err := dialer(smtp).Dial(); err != nil {47 logging.Warnf("Invalid SMTP configuration – service is disabled: %v", err)48 return nil, nil49 } else {50 _ = sc.Close()51 }52 templates, err := parseTemplates()53 if err != nil {54 return nil, errors.Wrap(err, "parse templates")55 }56 return &Service{57 smtp: smtp,58 templates: templates,59 }, nil60}61func (s *Service) IsConfigured() bool {62 return s != nil63}64func (s *Service) send(subject templateSubject, email, link string) error {65 if !s.IsConfigured() {66 return ErrSMTPNotConfigured67 }68 tmplt, ok := s.templates[subject]69 if !ok {70 return errors.Errorf("unknown email template: '%s'", subject)71 }72 msg := gomail.NewMessage()73 msg.SetHeader("From", s.smtp.From)74 msg.SetHeader("To", email)75 msg.SetHeader("Subject", subject.String())76 if s.smtp.ReplyTo != "" {77 msg.SetHeader("Reply-To", s.smtp.ReplyTo)78 }79 var body bytes.Buffer80 if err := tmplt.Execute(&body, templateValues{81 Email: email,82 Link: link,83 Signature: s.smtp.Signature,84 }); err != nil {85 return errors.Wrap(err, "transform email template")86 }87 msg.SetBody("text/html", body.String())88 dialer := gomail.NewDialer(s.smtp.Host, s.smtp.Port, s.smtp.User, s.smtp.Password)89 return dialer.DialAndSend(msg)90}91func (s *Service) SendResetPassword(email, link string) error {92 return s.send(resetPassword, email, link)93}94func (s *Service) SendAccountCreated(email, link string) error {95 return s.send(accountCreated, email, link)96}97func dialer(cfg *SMTPConfiguration) *gomail.Dialer {98 return gomail.NewDialer(cfg.Host, cfg.Port, cfg.User, cfg.Password)99}...

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 auth := smtp.PlainAuth(4 to := []string{"receiver email address"}5 msg := []byte("To: receiver email address\r6 err := smtp.SendMail("smtp.gmail.com:587", auth, "your email address", to, msg)7 if err != nil {8 log.Fatal(err)9 }10 fmt.Println("Email sent successfully")11}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Venom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful